utils.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from HTMLParser import HTMLParser
  2. import htmlentitydefs
  3. import csv
  4. import codecs
  5. import cStringIO
  6. class HTMLTextExtractor(HTMLParser):
  7. def __init__(self):
  8. HTMLParser.__init__(self)
  9. self.result = [ ]
  10. def handle_data(self, d):
  11. self.result.append(d)
  12. def handle_charref(self, number):
  13. codepoint = int(number[1:], 16) if number[0] in (u'x', u'X') else int(number)
  14. self.result.append(unichr(codepoint))
  15. def handle_entityref(self, name):
  16. codepoint = htmlentitydefs.name2codepoint[name]
  17. self.result.append(unichr(codepoint))
  18. def get_text(self):
  19. return u''.join(self.result)
  20. def html_to_text(html):
  21. s = HTMLTextExtractor()
  22. s.feed(html)
  23. return s.get_text()
  24. class UnicodeWriter:
  25. """
  26. A CSV writer which will write rows to CSV file "f",
  27. which is encoded in the given encoding.
  28. """
  29. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  30. # Redirect output to a queue
  31. self.queue = cStringIO.StringIO()
  32. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  33. self.stream = f
  34. self.encoder = codecs.getincrementalencoder(encoding)()
  35. def writerow(self, row):
  36. self.writer.writerow([(s.encode("utf-8").strip() if type(s) == str or type(s) == unicode else str(s)) for s in row])
  37. # Fetch UTF-8 output from the queue ...
  38. data = self.queue.getvalue()
  39. data = data.decode("utf-8")
  40. # ... and reencode it into the target encoding
  41. data = self.encoder.encode(data)
  42. # write to the target stream
  43. self.stream.write(data)
  44. # empty queue
  45. self.queue.truncate(0)
  46. def writerows(self, rows):
  47. for row in rows:
  48. self.writerow(row)