Nac*_*uel 0 python unicode encoding
我正在尝试做最简单的事情,打开一个文件,在python中读取并关闭它。简单。好的,这是代码:
name_file = open("Forever.txt", encoding='UTF-8')
data = name_file.read()
name_file.close()
print (data)
Run Code Online (Sandbox Code Playgroud)
我知道这些文本中有像心一样的表情符号。问题是这种表情符号没有像U + 2600这样的unicode语法,它们被放置为小图像。我认为以下错误是由于图像太小所致:
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f681' in
position 2333: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我尝试了以下操作,但未指定编码:
name_file = open("Forever.txt")
Run Code Online (Sandbox Code Playgroud)
错误更改为:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2303: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
不知道为什么会这样。
也许一种解决方案是将要测试的所有内容保存在变量中,然后删除其余的内容... mmm
任何帮助将不胜感激
您UnicodeEncodeError可能从您的print陈述中得到。正在正确读取和解释该文件,但是您只能打印控制台编码和字体实际支持的字符。该错误表明当前编码不支持该字符。
例如:
Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\U0001F681')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\U0001f681' in position 0: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
但是打印终端编码支持的字符,它可以工作:
>>> print('\U000000E0')
à
Run Code Online (Sandbox Code Playgroud)
我的控制台编码为cp437,但是如果我使用支持UTF-8编码的Python IDE,则可以使用:
>>> print('\U0001f681')
Run Code Online (Sandbox Code Playgroud)
您可能会或可能不会正确看到该字符。您需要使用支持该字符的字体。否则,您将获得一些默认的替换字符。