我在 python 3.3.4 中的“解码”方法遇到一些问题。这是我的代码:
for lines in open('file','r'):
decodedLine = lines.decode('ISO-8859-1')
line = decodedLine.split('\t')
但是我无法解码此问题的行:
AttributeError: 'str' object has no attribute 'decode'
你有什么想法吗?谢谢
一个编码字符串,一个解码字节。
您应该从文件中读取字节并解码它们:
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')
open
已经在 Python 3 中解码为 Unicode。如果您想将其作为字节打开,以便可以解码,则需要以“rb”模式打开。
在
PyJWT 2.0.0
版本之后没有 decode
方法,所以我们收到此错误。我们应该冻结以下版本以避免这个问题。
PyJWT==1.7.1
这可以让我在Python 3.6中顺利阅读中文文本。首先,将 str 转换为 bytes,然后对其进行解码。
for l in open('chinese2.txt','rb'):
decodedLine = l.decode('gb2312')
print(decodedLine)