在Python 3中,“str”对象没有“decode”属性

kr98yfug  于 4个月前  发布在  Python
关注(0)|答案(5)|浏览(68)

我在python 3.3.4中的decode方法中遇到了一些问题。这是我的代码:

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

字符串
但我无法解码这个问题的行:

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


你有什么想法吗?谢谢

brtdzjyr

brtdzjyr1#

一个对字符串进行 * 编码,一个对字节进行 * 解码。
你应该从文件中读取字节并解码它们:

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

ruoxqz4g

ruoxqz4g2#

open已经在Python 3中解码为Unicode,如果你以文本模式打开它。如果你想以字节打开它,那么你就可以解码,你需要以模式'rb'打开。

bnl4lu3b

bnl4lu3b3#

PyJWT 2.0.0版本没有decode方法之后,我们得到了这个错误。我们应该冻结下面的版本以避免这个问题。

PyJWT==1.7.1

字符串

dsekswqp

dsekswqp4#

这对我在Python 3.6中顺利阅读中文文本很有效。首先,将str转换为字节,然后解码它们。

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

字符串

rm5edbpk

rm5edbpk5#

在Python 3中,使用这个心理模型:

    • 编码 * 是将str对象转换为bytes对象的过程
    • 解码 * 是将bytes对象转换为str对象的过程


的数据
你得到了错误'str' object has no attribute 'decode'。如果你需要一个str,没有必要在它上面运行decode()。直接访问变量而不调用decode()

相关问题