Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

csv_utils.py 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # -*- coding: utf-8 -*-
  2. import codecs
  3. import csv
  4. import cStringIO
  5. # These classes are copied from http://docs.python.org/2/library/csv.html
  6. class CsvUnicodeWriter(object):
  7. """
  8. A CSV writer which will write rows to CSV file "f",
  9. which is encoded in the given encoding.
  10. """
  11. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  12. # Redirect output to a queue
  13. self.queue = cStringIO.StringIO()
  14. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  15. self.stream = f
  16. self.encoder = codecs.getincrementalencoder(encoding)()
  17. # Write BOM into file
  18. self.stream.write(codecs.BOM_UTF8)
  19. def cast_to_str(self, obj):
  20. if isinstance(obj, unicode):
  21. return obj.encode('utf-8')
  22. elif isinstance(obj, str):
  23. return obj
  24. elif hasattr(obj, '__unicode__'):
  25. return unicode(obj).encode('utf-8')
  26. elif hasattr(obj, '__str__'):
  27. return str(obj)
  28. else:
  29. raise TypeError('Expecting unicode, str, or object castable'
  30. ' to unicode or string, got: %r' % type(obj))
  31. def writerow(self, row):
  32. self.writer.writerow([self.cast_to_str(s) for s in row])
  33. # Fetch UTF-8 output from the queue ...
  34. data = self.queue.getvalue()
  35. data = data.decode("utf-8")
  36. # ... and reencode it into the target encoding
  37. data = self.encoder.encode(data)
  38. # write to the target stream
  39. self.stream.write(data)
  40. # empty queue
  41. self.queue.truncate(0)
  42. def writerows(self, rows):
  43. for row in rows:
  44. self.writerow(row)
  45. class UTF8Recoder(object):
  46. """
  47. Iterator that reads an encoded stream and reencodes the input to UTF-8
  48. """
  49. def __init__(self, f, encoding):
  50. self.reader = codecs.getreader(encoding)(f)
  51. def __iter__(self):
  52. return self
  53. def next(self):
  54. return self.reader.next().encode("utf-8")
  55. class CsvUnicodeReader(object):
  56. """
  57. A CSV reader which will iterate over lines in the CSV file "f",
  58. which is encoded in the given encoding.
  59. """
  60. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwargs):
  61. f = UTF8Recoder(f, encoding)
  62. self.reader = csv.reader(f, dialect=dialect, **kwargs)
  63. def next(self):
  64. row = self.reader.next()
  65. return [unicode(s, "utf-8") for s in row]
  66. def __iter__(self):
  67. return self