utils.py 2.7KB

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