【问题标题】:How can I convert encoding of special characters in python?如何在 python 中转换特殊字符的编码?
【发布时间】:2020-03-10 19:58:43
【问题描述】:

我有一个文件包含一些句子。但其中一些包含一些有线字符(√•、√§、√Ñ),如下所示。它们是什么,有没有办法将它们转换回 python 中的普通字符?

谢谢,

示例。

Is there an outdoor grill/bbq place? P√§r

Hej Hur långt aaär de till Stallarna? MVH LAILA

Är där sandstrand och hur långt

【问题讨论】:

  • 如果您知道应该用什么字符代替√•,请使用text = text.replac("√•", expected_char)。但也许这个文本使用不同的编码然后你用来解码它 - 即。 Latin1Latin2cp1250iso-8859-2 等。也许如果你使用不同的编码,那么你会得到正确的字符。
  • 或者您的系统可能使用不同的 UTF-8 编码。据我所知,MacOS 使用很少不同的编码,它可能会产生问题。顺便说一句:我在 Stackoverflow 上找到了这个:How to decode these characters? √° √© √≠

标签: python character-encoding


【解决方案1】:

看起来它使用了错误的编码 - MacRoman - 而不是 UTF-8。应该是MacOS系统吧。

如果我使用 MacRoman 将其编码(到字节),然后使用 utf-8 将其解码回字符串,那么我会得到正确的文本

text = '''Is there an outdoor grill/bbq place? P√§r

Hej Hur långt aaär de till Stallarna? MVH LAILA

Är där sandstrand och hur långt'''

text = text.encode('MacRoman').decode('utf-8') 
print(text)

结果:

Is there an outdoor grill/bbq place? Pär

Hej Hur långt aaär de till Stallarna? MVH LAILA

Är där sandstrand och hur långt

在 Linux Mint 19.2、Python 3.7 上测试

来自问题How to decode these characters? √° √© √≠的关于MacRoman的信息

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多