我有一個字符串(從 HTML 網頁請求獲得),其中包含特殊字符:'Dimarts, 10 Mar\\xe7 2020'如果我打印此字符串,它會正確轉義雙反斜杠并僅打印一個:Dimarts, 10 Mar\xe7 2020但我想要的是打印真實的字符,即字符 92 = ?Dimarts, 10 Mar? 2020我嘗試過用一個反斜杠替換雙反斜杠,甚至使用 html 庫取消轉義,但沒有成功。如果我用文本手動設置一個新變量,然后打印它,它會起作用:print('Original: ', repr(text))print('Direct : ', text)print('Option 1: ', text.replace('\\\\', '\\'))print('Option 2: ', text.replace(r'\\', '\\'))print('Option 3: ', text.replace(r'\\', chr(92)))print('Option 4: ', text.replace('\\', chr(92)))print('Option 5: ', html.unescape(text))text = 'Dimarts, 10 Mar\xe7 2020'print('Manual: ', text)結果卻從來沒有像預期的那樣:Original: 'Dimarts, 10 Mar\\xe7 2020'Direct : Dimarts, 10 Mar\xe7 2020Option 1: Dimarts, 10 Mar\xe7 2020Option 2: Dimarts, 10 Mar\xe7 2020Option 3: Dimarts, 10 Mar\xe7 2020Option 4: Dimarts, 10 Mar\xe7 2020Option 5: Dimarts, 10 Mar\xe7 2020Manual: Dimarts, 10 Mar? 2020有沒有辦法讓Python正確處理特殊字符?
2 回答

慕妹3242003
TA貢獻1824條經驗 獲得超6個贊
好吧,事實證明我在 Windows 中對文件進行編碼時遇到了問題。我必須在處理之前對其進行解碼。因此,這樣做解決了問題:
htmlfile = urllib.request.urlopen('http://www.somewebpage.com/')
for line in htmlfile:
line = line.decode('cp1252')
也可以解碼整個 html:
htmlfile = urllib.request.urlopen('http://www.somewebpage.com/').read()
htmldecoded = htmlfile.decode('cp1252')
這樣做解決了問題,我可以正確打印字符串。
- 2 回答
- 0 關注
- 205 瀏覽
添加回答
舉報
0/150
提交
取消