我在将 unicode CSV 字符串读入 python-unicodescv 时遇到问题:
>>> import unicodecsv, StringIO
>>> f = StringIO.StringIO(u'é,é')
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/guy/test/.env/lib/python2.7/site-packages/unicodecsv/__init__.py", line 101, in next
row = self.reader.next()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
我猜这是我如何将 unicode 字符串转换为 StringIO 文件的问题? python-unicodecsv github 页面上的示例运行良好:
>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ
使用 cStringIO 尝试我的代码失败,因为 cStringIO 无法接受 unicode (所以为什么这个示例有效,我不知道!)
>>> from cStringIO import StringIO
>>> f = StringIO(u'é')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
我需要接受来自 Web 文本区域表单字段的 UTF-8 CSV 格式的输入,因此不能只从文件中读入。
有任何想法吗?