【问题标题】:Decode french accent not working with utf-8解码法语口音不适用于 utf-8
【发布时间】:2020-04-27 15:57:33
【问题描述】:

我尝试解码这个非常简单的变量b'autorite nt\\syst\x8ame\r\n'

b'autorite nt\\syst\x8ame\r\n'
>>> t.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8a in position 16: invalid start byte

但没有任何效果,它应该打印 autorite nt\\système 但我找不到正确打印它的方法

【问题讨论】:

    标签: python python-3.x utf-8 character-encoding


    【解决方案1】:

    它没有被编码为 UTF-8。它可能是 cp437 或以下任何一种:cp437、cp720、cp850、cp857、cp858、cp860、cp861、cp863、cp865 (source)

    >>> print(b'autorite nt\\syst\x8ame\r\n'.decode('cp437'))
    autorite nt\système
    

    【讨论】:

    • 有没有办法更通用一点?如果下一个字节不是 'cp437' 编码的呢?
    • 如果您的字节包含具有多种编码的文本,那么您将遇到困难。有像 chardet 这样的工具会尝试猜测字节串的编码,但是对于混合编码的字节没有通用的解决方案。
    【解决方案2】:

    您可以将解码与utf-8 编码和替换规则一起使用。

    t = b'autorite nt\\syst\x8ame\r\n'
    t.decode('utf-8', 'replace')
    

    进一步阅读: https://docs.python.org/3/howto/unicode.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2016-06-05
      • 1970-01-01
      相关资源
      最近更新 更多