UnicodeCSV读取器从Unicode字符串无法工作?

2024-06-01 07:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在将unicode CSV字符串读入python unicode Descv时遇到问题:

>>> 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 unicodesv github页面上的示例运行良好:

^{pr2}$

用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)

我需要接受一个来自webtextarea表单域的UTF-8csv格式的输入,因此不能仅仅从文件中读入。在

有什么想法吗?在


Tags: 字符串inimportmostlineunicodereaderfile
1条回答
网友
1楼 · 发布于 2024-06-01 07:08:46

unicodecsv文件为您读取并解码字节字符串。而是传递unicode字符串。在输出时,您的unicode值将使用配置的编解码器编码为bytestrings。在

此外,cStringIO.StringIO只能处理由testrings编码的内容,而纯python StringIO.StringIO类很乐意将unicode值视为字节字符串。在

解决方案是在将unicode值放入StringIO对象之前对unicode值进行编码:

>>> import unicodecsv, StringIO, cStringIO
>>> f = StringIO.StringIO(u'é,é'.encode('utf8'))
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> next(r)
[u'\xe9', u'\xe9']
>>> f = cStringIO.StringIO(u'é,é'.encode('utf8'))
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> next(r)
[u'\xe9', u'\xe9']

相关问题 更多 >