【问题标题】:Encoding and Decoding special characters (Latin-1)编码和解码特殊字符 (Latin-1)
【发布时间】:2019-12-09 21:43:43
【问题描述】:

我正在尝试在我的 HTML 解析之后清除一些奇怪的 unicode 字符,但仍然没有转换这些 un​​icode。

原文:

raw = 'If further information is needed, don´t hesitate to contact us. Kind regards, José Ramirez.'

编解码后:

text = str(raw.encode().decode('unicode_escape'))

当前输出:

'If further information is needed, donÃ\x82´t hesitate to contact us. Kind regards, JosÃ\x83© Ramirez'

期望的输出:

'If further information is needed, don´t hesitate to contact us. Kind regards, José Ramirez'

【问题讨论】:

    标签: python-3.x decode python-unicode unicode-string


    【解决方案1】:

    你做错了。您的raw.encode().decode('unicode_escape') 的效果与raw.encode('utf-8').decode('latin-1') 相同。你真正想要的:

    >>> raw.encode('latin-1').decode('utf-8')
    'If further information is needed, don´t hesitate to contact us. Kind regards, José Ramirez.'
    

    您的字符串来自使用 UTF-8 编码文本的人,但假设它是 Latin-1。

    如果您有许多不同的 Mojibake 变体(文本解码不正确,导致乱码),ftfy 软件包可以提供帮助:

    >>> import ftfy
    >>> ftfy.fix_text('If further information is needed, don´t hesitate to contact us. Kind regards, José Ramirez.')
    'If further information is needed, don´t hesitate to contact us. Kind regards, José Ramirez.'
    

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多