123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. self.result.append(name)
  19. def get_text(self):
  20. return u''.join(self.result)
  21. def html_to_text(html):
  22. s = HTMLTextExtractor()
  23. s.feed(html)
  24. return s.get_text()
  25. class UnicodeWriter:
  26. """
  27. A CSV writer which will write rows to CSV file "f",
  28. which is encoded in the given encoding.
  29. """
  30. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  31. # Redirect output to a queue
  32. self.queue = cStringIO.StringIO()
  33. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  34. self.stream = f
  35. self.encoder = codecs.getincrementalencoder(encoding)()
  36. def writerow(self, row):
  37. self.writer.writerow([(s.encode("utf-8").strip() if type(s) == str or type(s) == unicode else str(s)) for s in row])
  38. # Fetch UTF-8 output from the queue ...
  39. data = self.queue.getvalue()
  40. data = data.decode("utf-8")
  41. # ... and reencode it into the target encoding
  42. data = self.encoder.encode(data)
  43. # write to the target stream
  44. self.stream.write(data)
  45. # empty queue
  46. self.queue.truncate(0)
  47. def writerows(self, rows):
  48. for row in rows:
  49. self.writerow(row)