我试图将包含表情符号的字符串保存到.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抓取了字符串
此方法以前曾起作用,但我不知道为什么此代码不起作用。我试图在其他地方找到答案,但不幸的是没有成功。
我希望有人有一个主意:)
答案 0 :(得分:1)
You're trying to decode a string that has already been decoded.如果您的文件设置为utf-8,但其中仅包含ASCII字符,则我认为编码无关紧要。
一旦有了str
,就不再需要对其进行解码了。如果您放弃.decode('utf-8')
,该错误可能会消失。
如果您期望代码可能具有utf-8值,则可以用try-except
块将其包围以捕获AttributeError
,然后对其进行相应的操作。