[英]Unable to decode string to utf-8 in python
我正在嘗試將包含表情符號的字符串保存到 .txt 文件中,但在運行代碼時總是出現錯誤。
代碼:
I set the .txt file up to have an utf-8 encoding.
subject_proper = subject.text.strip()
subject_proper = subject_proper.decode('utf-8')
錯誤:
subject_proper = subject_proper.decode('utf-8')
AttributeError: 'str' object has no attribute 'decode'
編輯:
如果我刪除 .decode 我會收到以下錯誤:
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 65-65: Non-BMP character not supported in Tk
編輯2:
示例文本:鐵人三項運動員的聖誕禮物 ⛄
我已經從https://milled.com/wiggle-co-uk 中抓取了字符串
這種方法以前有用過,但我不知道為什么用這段代碼不行。 我試圖在別處找到答案,但不幸的是沒有成功。
我希望有人有想法:)
您正在嘗試對已解碼的字符串進行解碼。 如果您的文件設置為 utf-8 但其中只有 ASCII 字符,我認為編碼無關緊要。
一旦你有了str
,就不需要再解碼它了。 如果刪除.decode('utf-8')
,錯誤可能會消失。
如果您希望代碼可能具有 utf-8 值,您可以用try-except
塊包圍它以捕獲AttributeError
,然后對其進行相應的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.