gpt4 book ai didi

Python CSV 文件 UTF-16 到 UTF-8 打印错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:31:05 24 4
gpt4 key购买 nike

网上有很多关于这个问题的话题,但我似乎找不到适合我的具体情况的答案。

我有一个 CSV 文件。我不确定对它做了什么,但是当我尝试打开它时,我得到:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

这是一个完整的Traceback:

Traceback (most recent call last):
File "keywords.py", line 31, in <module>
main()
File "keywords.py", line 28, in main
get_csv(file_full_path)
File "keywords.py", line 19, in get_csv
for row in reader:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u5a07' in position 10: ordinal not in range(128)

在 Stack Overflow 的帮助下,我通过以下方式打开它:

reader = csv.reader(codecs.open(file_full_path, 'rU', 'UTF-16'), delimiter='\t', quotechar='"')

现在的问题是,当我读取文件时:

def get_csv(file_full_path):
import csv, codecs
reader = csv.reader(codecs.open(file_full_path, 'rU', 'UTF-16'), delimiter='\t', quotechar='"')
for row in reader:
print row

我卡在了亚洲符号上:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u5a07' in position 10: ordinal not in range(128)

我已经在包含该字符的字符串上尝试了 decode、'encode'、unicode(),但似乎没有帮助。

for row in reader:
#decoded_row = [element_s.decode('UTF-8') for element_s in row]
#print decoded_row
encoded_row = [element_s.encode('UTF-8') for element_s in row]
print encoded_row

在这一点上我真的不明白为什么。如果我

>>> print u'\u5a07'

>>> print '娇'

它有效。同样在终端中,它也有效。我检查了终端和 Python shell 上的默认编码,到处都是 UTF-8。它很容易打印出那个符号。我认为这与我使用 UTF-16 使用 codecs 打开文件有关。

我不确定从这里去哪里。有人能帮忙吗?

最佳答案

csv 模块不能处理 Unicode 输入。它在其 documentation page 上特别说明:

Note: This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe;

您需要将 CSV 文件转换为 UTF-8 以便模块可以处理它:

with codecs.open(file_full_path, 'rU', 'UTF-16') as infile:
with open(file_full_path + '.utf8', 'wb') as outfile:
for line in infile:
outfile.write(line.encode('utf8'))

或者,您可以使用命令行实用程序 iconv为您转换文件。

然后使用重新编码的文件读取您的数据:

 reader = csv.reader(open(file_full_path + '.utf8', 'rb'), delimiter='\t', quotechar='"')
for row in reader:
print [c.decode('utf8') for c in row]

请注意,这些列随后需要手动解码为 un​​icode。

关于Python CSV 文件 UTF-16 到 UTF-8 打印错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com