【发布时间】:2017-08-24 09:00:13
【问题描述】:
我从 csv 文件中读取文本时遇到问题。 csv 文件中的示例行如下所示:"
1477-7819-4-45-2 血管淋巴浸润 (H & E 400 Ã)。"
我猜是文本的编码有问题,所以我决定把它改成ASCII。
这是我目前的python代码:
text_path = '/some_path/filename.csv'
text_path_ascii = '/some_path/filename_ASCII.csv'
input_codec = 'UTF-16'
output_codec = 'ASCII'
for line in unicode_file:
unicode_data = unicode_file.read().decode(input_codec)
#here is another problem => AttributeError: 'str' object has no attribute 'decode'
unicode_data = unicode_file.read()
ascii_file = open(text_path_ascii, 'w')
ascii_file.write(unicode_data.write(unicode_data.encode(output_codec)))
# same problem=> AttributeError: 'str' object has no attribute 'encode'
ascii_file.write(unicode_data.encode(output_codec))
所以我的问题是我不知道如何编码/解码文本。
我什至不确定这是否是正确处理错误书面文本的正确方法(是的,如果你用任何编辑器打开它,文本看起来就像给定的行)。
或者是否有一种更简单的方法可以直接读取 csv 文本而没有“损坏”字符)?
感谢您的想法
【问题讨论】:
-
哎呀,我不能完全理解你在这里想要做什么,但你走错了路! str 对象在 Python3 中应具有 encode 方法,在 Python2 中应具有 decode 方法。没有它们是发生错误的证据。不幸的是,Python2 和 Python3 都能够处理非 ascii csv 文件。因此,说出您使用的 Python 版本(Python3 对 unicode 更友好),显示输入文件的一些行并说出它的编码是什么。然后我们可以说如何将其加载为 csv 文件...
-
要尝试的第一件事(也是最后一个)是使用编写它的编码读取文本文件。如果您没有收到包含文件、规范或文档的信息,请将其发回。如果您通过 HTTP 接收文件,可能会有一个 Content-Type 标头告诉您编码(“字符集”)是什么。
标签: python csv encoding ascii utf