utils.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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>',
  25. content, flags=re.I | re.U)
  26. else:
  27. regex_parts = []
  28. for chunk in query.split():
  29. if len(chunk) == 1:
  30. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  31. else:
  32. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  33. query_regex = u'({0})'.format('|'.join(regex_parts))
  34. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  35. content, flags=re.I | re.U)
  36. return content
  37. class HTMLTextExtractor(HTMLParser):
  38. def __init__(self):
  39. HTMLParser.__init__(self)
  40. self.result = []
  41. def handle_data(self, d):
  42. self.result.append(d)
  43. def handle_charref(self, number):
  44. if number[0] in (u'x', u'X'):
  45. codepoint = int(number[1:], 16)
  46. else:
  47. codepoint = int(number)
  48. self.result.append(unichr(codepoint))
  49. def handle_entityref(self, name):
  50. #codepoint = htmlentitydefs.name2codepoint[name]
  51. #self.result.append(unichr(codepoint))
  52. self.result.append(name)
  53. def get_text(self):
  54. return u''.join(self.result)
  55. def html_to_text(html):
  56. s = HTMLTextExtractor()
  57. s.feed(html)
  58. return s.get_text()
  59. class UnicodeWriter:
  60. """
  61. A CSV writer which will write rows to CSV file "f",
  62. which is encoded in the given encoding.
  63. """
  64. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  65. # Redirect output to a queue
  66. self.queue = cStringIO.StringIO()
  67. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  68. self.stream = f
  69. self.encoder = getincrementalencoder(encoding)()
  70. def writerow(self, row):
  71. unicode_row = []
  72. for col in row:
  73. if type(col) == str or type(col) == unicode:
  74. unicode_row.append(col.encode('utf-8').strip())
  75. else:
  76. unicode_row.append(col)
  77. self.writer.writerow(unicode_row)
  78. # Fetch UTF-8 output from the queue ...
  79. data = self.queue.getvalue()
  80. data = data.decode("utf-8")
  81. # ... and reencode it into the target encoding
  82. data = self.encoder.encode(data)
  83. # write to the target stream
  84. self.stream.write(data)
  85. # empty queue
  86. self.queue.truncate(0)
  87. def writerows(self, rows):
  88. for row in rows:
  89. self.writerow(row)