'str' 对象在 Python3 中没有属性 'decode'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26125141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'str' object has no attribute 'decode' in Python3
提问by hasmet
I've some problem with "decode" method in python 3.3.4. This is my code:
我在 python 3.3.4 中的“解码”方法有一些问题。这是我的代码:
for lines in open('file','r'):
decodedLine = lines.decode('ISO-8859-1')
line = decodedLine.split('\t')
But I can't decode the line for this problem:
但我无法解码此问题的行:
AttributeError: 'str' object has no attribute 'decode'
Do you have any ideas? Thanks
你有什么想法?谢谢
采纳答案by Veedrac
One encodesstrings, and one decodesbytes.
一种编码字符串,一种解码字节。
You should read bytes from the file and decode them:
您应该从文件中读取字节并对其进行解码:
for lines in open('file','rb'):
decodedLine = lines.decode('ISO-8859-1')
line = decodedLine.split('\t')
Luckily openhas an encoding argument which makes this easy:
幸运的是,open有一个编码参数可以让这变得简单:
for decodedLine in open('file', 'r', encoding='ISO-8859-1'):
line = decodedLine.split('\t')
回答by Daniel Roseman
openalready decodes to Unicode in Python 3 if you open in text mode. If you want to open it as bytes, so that you can then decode, you need to open with mode 'rb'.
open如果您以文本模式打开,则已经在 Python 3 中解码为 Unicode。如果你想以字节的形式打开它,这样你就可以解码,你需要用'rb'模式打开。
回答by Sarah
This works for me smoothly to read Chinese text in Python 3.6. First, convert str to bytes, and then decode them.
这对我在 Python 3.6 中顺利阅读中文文本很有效。首先,将 str 转换为字节,然后对其进行解码。
for l in open('chinese2.txt','rb'):
decodedLine = l.decode('gb2312')
print(decodedLine)

