1 回答
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的 utf-8 被解碼為 cp1250。
我在 python3 中所做的是:
orig = "Za?ó?? g??l? ja?ń"
wrong = "Za???????? g????l?… ja????"
for enc in range(437, 1300):
try:
res = orig.encode().decode(f"cp{enc}")
if res == wrong:
print('FOUND', res, enc)
except:
pass
...結(jié)果是 1250 代碼頁。
所以你的解決方案應(yīng)該是:
import sys
def restore(garbaged):
# python 3
if sys.version_info.major > 2:
return garbaged.encode('cp1250').decode()
# python 2
else:
# is it a string
try:
return garbaged.decode('utf-8').encode('cp1250')
# or is it unicode
except UnicodeEncodeError:
return garbaged.encode('cp1250')
編輯:
"高生旺"無法恢復(fù)的原因é??”??—?:
"高生旺".encode('utf-8')是b'\xe9\xab\x98\xe7\x94\x9f\xe6\x97\xba'。
問題是\x98部分。在 cp1250 中,該值沒有字符集。如果你試試這個(gè):
"高生旺".encode('utf-8').decode('cp1250')
你會(huì)得到這個(gè)錯(cuò)誤:UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 2: character maps to <undefined>
獲取方式"é??”??—?"為:
"高生旺".encode('utf-8').decode('cp1250', 'ignore')
但是這ignore部分很關(guān)鍵,它會(huì)導(dǎo)致數(shù)據(jù)丟失:
'é??”??—?'.encode('cp1250')是b'\xe9\xab\xe7\x94\x9f\xe6\x97\xba'。
如果你比較這兩個(gè):
b'\xe9\xab\xe7\x94\x9f\xe6\x97\xba'
b'\xe9\xab\x98\xe7\x94\x9f\xe6\x97\xba'
您會(huì)看到該\x98字符丟失,因此當(dāng)您嘗試恢復(fù)原始內(nèi)容時(shí),您會(huì)得到一個(gè)UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte.
如果你試試這個(gè):
'é??”??—?'.encode('cp1250').decode('utf-8', 'backslashreplace')
結(jié)果將是'\\xe9\\xab生旺'。\xe9\xab\x98可以解碼為高,從\xe9\xab它是不可能的。
添加回答
舉報(bào)
