utils.py 2.6 KB

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