【发布时间】:2019-04-07 11:59:47
【问题描述】:
强制性介绍,指出我做了一些研究
这似乎应该很简单(如果找到合适的目标问题,我很乐意作为重复关闭),但我对字符编码以及 Python 如何处理它们以自己解决问题还不够熟悉。冒着看起来懒惰的风险,我会很好地注意到答案可能在下面的链接之一中,但我还没有在阅读中看到它。
我参考了一些文档:Unicode HOWTO、codecs.py docs
我还查看了一些投票率很高的旧 SO 问题:Writing Unicode text to a text file?、Python, Unicode, and the Windows console
问题
这是一个演示我的问题的MCVE 代码示例:
with open('foo.txt', 'wt') as outfile:
outfile.write('\u014d')
回溯如下:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Users\cashamerica\AppData\Local\Programs\Python\Python3\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u014d' in position 0: character maps to <undefined>
我很困惑,因为代码点 U+014D 是 'ō',分配的代码点 LATIN SMALL LETTER O WITH MACRON (official Unicode source)
我什至可以将字符打印到 Windows 控制台(但它呈现为普通的“o”):
>>> print('\u014d')
o
【问题讨论】:
-
您正在尝试将其编码为 CP1252,其中不存在此字母。
标签: python python-3.x unicode codec