我需要转换一个字符串,以便将它转换成人类可读的格式。
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."
但我面临着多重问题。不同的场景。
print(str(s.encode('cp1252',"ignore"),'utf-8'))时
UnicodeDecodeError:'utf-8‘编解码器无法解码位置4的字节0x92print(str(s.encode('cp1252'),'utf-8',"ignore"))时
UnicodeEncodeError:“charmap”编解码器无法对151号位置的字符“\u2015”进行编码print(str(s.encode('cp1252',"ignore"),'utf-8',"ignore"))时,正如可以预测的那样,在省略了所有撇号(单引号和双引号)之后,我得到了字符串,没有错误。
“这太可怕了,找到了最好的格言,音乐给了宇宙一个灵魂,给了心灵翅膀,给了想象力,给了一切生命。柏拉图。”发布于 2018-10-01 18:22:18
我什么都试过了,但我一个人解决不了。一个更简单的搜索方法是s.encode('utf-8',“忽略”).decode(“utf-8”,忽略)。我尝试了latin1,ascii,cp1252和utf8,utf16的组合,然后放弃了。我一个接一个地尝试了python编码的这份清单编码。然后我寻找能够检测到同样更聪明的代码。
然后我来到了博客文章,它解释了在修改编码过程中可能出错的所有事情。他们提出的解决方案是对所有编码进行全面搜索,以找到正确的.。
这个包叫做ftfy。
免责声明:我与ftfy无关。我今天才看到的。
pip安装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))这太可怕了,“音乐给宇宙一个灵魂,给心灵以翅膀,给想象力飞翔,给一切以生命。”-柏拉图。
https://stackoverflow.com/questions/52595809
复制相似问题