【问题标题】:'str' object has no attribute 'decode' in Python3'str' 对象在 Python3 中没有属性 'decode'
【发布时间】:2014-11-25 08:03:47
【问题描述】:

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'

你有什么想法吗?谢谢

【问题讨论】:

标签: python python-3.x python-3.3


【解决方案1】:

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

PyJWT==1.7.1

【讨论】:

    【解决方案2】:

    这让我在 Python 3.6 中顺利阅读中文文本。首先将str转换为字节,然后解码。

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

    【讨论】:

      【解决方案3】:

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

      您应该从文件中读取字节并对其进行解码:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2014-05-26
          • 2015-05-15
          • 1970-01-01
          • 2021-07-09
          • 2022-01-21
          • 2018-12-01
          • 1970-01-01
          • 2021-07-05
          • 2021-10-30
          相关资源
          最近更新 更多