utils.py 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from HTMLParser import HTMLParser
  2. #import htmlentitydefs
  3. import csv
  4. from codecs import getincrementalencoder
  5. import cStringIO
  6. import re
  7. def gen_useragent():
  8. # TODO
  9. ua = "Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0"
  10. return ua
  11. def highlight_content(content, query):
  12. if not content:
  13. return None
  14. # ignoring html contents
  15. # TODO better html content detection
  16. if content.find('<') != -1:
  17. return content
  18. query = query.decode('utf-8')
  19. if content.lower().find(query.lower()) > -1:
  20. query_regex = u'({0})'.format(re.escape(query))
  21. content = re.sub(query_regex, '<b>\\1</b>', content, flags=re.I | re.U)
  22. else:
  23. regex_parts = []
  24. for chunk in query.split():
  25. if len(chunk) == 1:
  26. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  27. else:
  28. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  29. query_regex = u'({0})'.format('|'.join(regex_parts))
  30. content = re.sub(query_regex, '<b>\\1</b>', content, flags=re.I | re.U)
  31. return content
  32. class HTMLTextExtractor(HTMLParser):
  33. def __init__(self):
  34. HTMLParser.__init__(self)
  35. self.result = []
  36. def handle_data(self, d):
  37. self.result.append(d)
  38. def handle_charref(self, number):
  39. if number[0] in (u'x', u'X'):
  40. codepoint = int(number[1:], 16)
  41. else:
  42. codepoint = int(number)
  43. self.result.append(unichr(codepoint))
  44. def handle_entityref(self, name):
  45. #codepoint = htmlentitydefs.name2codepoint[name]
  46. #self.result.append(unichr(codepoint))
  47. self.result.append(name)
  48. def get_text(self):
  49. return u''.join(self.result)
  50. def html_to_text(html):
  51. s = HTMLTextExtractor()
  52. s.feed(html)
  53. return s.get_text()
  54. class UnicodeWriter:
  55. """
  56. A CSV writer which will write rows to CSV file "f",
  57. which is encoded in the given encoding.
  58. """
  59. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  60. # Redirect output to a queue
  61. self.queue = cStringIO.StringIO()
  62. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  63. self.stream = f
  64. self.encoder = getincrementalencoder(encoding)()
  65. def writerow(self, row):
  66. unicode_row = []
  67. for col in row:
  68. if type(col) == str or type(col) == unicode:
  69. unicode_row.append(col.encode('utf-8').strip())
  70. else:
  71. unicode_row.append(col)
  72. self.writer.writerow(unicode_row)
  73. # Fetch UTF-8 output from the queue ...
  74. data = self.queue.getvalue()
  75. data = data.decode("utf-8")
  76. # ... and reencode it into the target encoding
  77. data = self.encoder.encode(data)
  78. # write to the target stream
  79. self.stream.write(data)
  80. # empty queue
  81. self.queue.truncate(0)
  82. def writerows(self, rows):
  83. for row in rows:
  84. self.writerow(row)