首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python更改字符串编码时出错。UTF-8 & cp1252

使用python更改字符串编码时出错。UTF-8 & cp1252
EN

Stack Overflow用户
提问于 2018-10-01 17:12:27
回答 1查看 615关注 0票数 1

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

代码语言:javascript
复制
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."

但我面临着多重问题。不同的场景。

  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"))时,正如可以预测的那样,在省略了所有撇号(单引号和双引号)之后,我得到了字符串,没有错误。 “这太可怕了,找到了最好的格言,音乐给了宇宙一个灵魂,给了心灵翅膀,给了想象力,给了一切生命。柏拉图。”
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-01 18:22:18

我什么都试过了,但我一个人解决不了。一个更简单的搜索方法是s.encode('utf-8',“忽略”).decode(“utf-8”,忽略)。我尝试了latin1,ascii,cp1252和utf8,utf16的组合,然后放弃了。我一个接一个地尝试了python编码的这份清单编码。然后我寻找能够检测到同样更聪明的代码。

然后我来到了博客文章,它解释了在修改编码过程中可能出错的所有事情。他们提出的解决方案是对所有编码进行全面搜索,以找到正确的.

这个包叫做ftfy。

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

pip安装ftfy

代码语言:javascript
复制
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))

这太可怕了,“音乐给宇宙一个灵魂,给心灵以翅膀,给想象力飞翔,给一切以生命。”-柏拉图。

这解决了问题。有关如何修复它的更多信息,请参见ftfy 这里或docs 这里的源代码。:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52595809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档