解码乱码
当你遇到错误解码的字符时,怎么才能找到原始字符串的可能候选者呢?
Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb.png
我知道这个图片文件名应该是一些日文字符。但是我尝试了很多方法,比如用urllib进行编码和解码,尝试iso8859-1和utf8的编码,但还是没法恢复出原来的文件名。
这种损坏是可以逆转的吗?
1 个回答
5
你可以使用 chardet(用 pip 安装):
import chardet
your_str = "Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb"
detected_encoding = chardet.detect(your_str)["encoding"]
try:
correct_str = your_str.decode(detected_encoding)
except UnicodeDecodeError:
print("Could not estimate encoding")
结果是:時間試験観点(アニメパス)_10秒(我不知道这是否正确)
对于 Python 3(源文件编码为 utf8):
import chardet
import codecs
falsely_decoded_str = "Ä×èÈÄÄî¦è¤ô_üiâAâjâüâpâXüj_10òb"
try:
encoded_str = falsely_decoded_str.encode("cp850")
except UnicodeEncodeError:
print("could not encode falsely decoded string")
encoded_str = None
if encoded_str:
detected_encoding = chardet.detect(encoded_str)["encoding"]
try:
correct_str = encoded_str.decode(detected_encoding)
except UnicodeEncodeError:
print("could not decode encoded_str as %s" % detected_encoding)
with codecs.open("output.txt", "w", "utf-8-sig") as out:
out.write(correct_str)
总结一下:
>>> s = 'Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb.png'
>>> s.encode('cp850').decode('shift-jis')
'時間試験観点(アニメパス)_10秒.png'