当您遇到解码错误的字符时,如何确定可能是原始字符串的候选项?
Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb.png
我知道这个图片文件名本应该是一些日文字符。但是在尝试使用urllib进行引用/取消引用、对iso8859-1和utf8进行编码和解码的过程中,我无法还原并获得原始文件名。
这种损坏是否可以逆转?
Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb.png
我知道这个图片文件名本应该是一些日文字符。但是在尝试使用urllib进行引用/取消引用、对iso8859-1和utf8进行编码和解码的过程中,我无法还原并获得原始文件名。
这种损坏是否可以逆转?
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")
结果:时间测试视角(Anime Pass)_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'
Ä×èÈÄÄî▒è¤ô_üiâAâjâüâpâXüj_10òb
是以代码页932编码(类似Shift-JIS)的字符串被错误地解释为代码页850(DOS西欧)而得到的,因此上述源代码需要以cp850格式保存才能正常工作。 - bobince