utils.py 3.2 KB

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