python - 来自 unicode 字符串的 unicodecsv 阅读器不起作用?

标签 python csv unicode

我在将 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)

我需要接受来自网络文本区域表单域的 UTF-8 CSV 格式输入,因此不能只从文件中读入。

有什么想法吗?

最佳答案

unicodecsv 文件为您读取和解码字节串。您正在向它传递 unicode 字符串。在输出时,您的 unicode 值会使用配置的编解码器为您编码为字节串。

此外,cStringIO.StringIO 只能处理编码的字节串,而纯 python StringIO.StringIO 类很乐意将 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']

关于python - 来自 unicode 字符串的 unicodecsv 阅读器不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21479589/

相关文章:

python - 如何从 netcdf 文件中提取投影在不规则网格上的变量的像素值?

python - 如何在 PYTHON 中特别是在 LINUX 中使用 TKINTER 在工具栏上插入自定义图标?

python - Python 中平滑图形的问题

c# - 在 CSV 文件中编辑/保存一行

python - 将 1000 个文本文件转换为单个 csv 文件

java - 从文本读取 srt 文件时出现奇怪的字符

python - 如何在 Python (Trello) 中为 POST 函数编写单元测试?

python - 有没有办法找到Python中存在*.csv?

python - 如何正确解码以十进制书写的字符串中的转义序列

python - XMLRunner - "unicode object has no attribute ' 构建时写入“”