“str”对象在Python3中没有“decode”属性

2024-05-19 12:35:11 发布

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

我对Python3.3.4中的“decode”方法有些问题。这是我的代码:

for lines in open('file','r'):
    decodedLine = lines.decode('ISO-8859-1')
    line = decodedLine.split('\t')

但我无法破解这个问题:

AttributeError: 'str' object has no attribute 'decode'

你有什么想法吗?谢谢


Tags: 方法代码inforobjectlineisoopen
3条回答

这对我顺利阅读Python3.6中的中文文本很有帮助。首先,将str转换为字节,然后对它们进行解码。

for l in open('chinese2.txt','rb'):
    decodedLine = l.decode('gb2312')
    print(decodedLine)

如果以文本模式打开,open已经在Python 3中解码为Unicode。如果你想以字节的形式打开它,这样你就可以解码,你需要用“rb”模式打开它。

一个编码字符串,一个解码字节。

您应该从文件中读取字节并解码它们:

for lines in open('file','rb'):
    decodedLine = lines.decode('ISO-8859-1')
    line = decodedLine.split('\t')

幸运的是,open有一个编码参数,这使得这很容易:

for decodedLine in open('file', 'r', encoding='ISO-8859-1'):
    line = decodedLine.split('\t')

相关问题 更多 >