【问题标题】:Error while changing the encoding of a String with python. UTF-8 & cp1252使用 python 更改字符串的编码时出错。 UTF-8 和 cp1252
【发布时间】:2018-10-01 17:12:27
【问题描述】:

我需要转换一个字符串,以便将其转换为人类可读的格式。

s = "that’s awful, Find – Best Quotes, “Music gives a soul to the universe, wings to the mind, flight to the imagination and life to everything.” ― Plato."

我想将此字符串转换为"that’s awful, Find - Best Quotes, "Music gives a soul to the universe, wings to the mind, flight to the imagination and life to everything." ― Plato."

但我面临多个问题 w.r.t.不同的场景。

  1. 当我使用print(str(s.encode('cp1252',"ignore"),'utf-8')) 我明白了

    UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 4 中的字节 0x92

  2. 当我使用print(str(s.encode('cp1252'),'utf-8',"ignore")) 我明白了

    UnicodeEncodeError: 'charmap' 编解码器无法对位置 151 中的字符 '\u2015' 进行编码

  3. 当我使用print(str(s.encode('cp1252',"ignore"),'utf-8',"ignore")) 然后可以预见,在省略所有撇号、单引号和双引号后,我得到的字符串没有错误

    “那太可怕了,查找 – 最佳语录,音乐赋予宇宙灵魂,赋予思想翅膀,飞向想象,赋予一切生命。柏拉图。”

【问题讨论】:

  • 所以第三种情况是有效的。似乎忽略转换中的错误有助于不引发错误并且字符串转换。还有一个错字是案例3,它是s.encode而不是string.encode
  • 但我不想松开撇号、单引号和双引号。所以基本上忽略错误是行不通的。

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


【解决方案1】:

我尝试了所有方法,但我无法自己修复它。执行相同搜索的更简单方法是 s.encode('utf-8', "ignore").decode("utf-8", ignore)。我尝试了latin1,ascii,cp1252和utf8,utf16的组合并放弃了。 我从python编码的this list一一尝试了编码。然后我寻找可以更智能地检测到相同的代码。

然后我来了a blog post,它解释了在修复编码时可能出错的所有事情。他们提出的解决方案是对所有编码进行全面搜索以找到正确的编码。

这个包叫做 ftfy。

免责声明:我与 ftfy 无关。我今天才看到。

pip install ftfy

s = "that’s awful, Find – Best Quotes, “Music gives a soul to the universe, wings to the mind, flight to the imagination and life to everything.” ― Plato."

import ftfy

print(ftfy.fix_text(s))

这太糟糕了,Find – Best Quotes,“音乐赋予宇宙灵魂, 心灵的翅膀,想象力的飞翔和一切的生命。” ——柏拉图。

这解决了问题。 有关他们如何修复它的更多信息,请参阅 ftfy here 或文档 here 的源代码。 :)

【讨论】:

  • 很高兴知道它在性能/规模方面有效,数据集有多大以及多少秒?
  • 我在大约 2-3 秒内处理了 200k 个字符的数据集。它实际上是一个 csv。
猜你喜欢
  • 2016-01-11
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多