【发布时间】:2017-04-30 21:19:16
【问题描述】:
我的程序使用requests 从网络服务器获取 JSON 字符串。然后它转换为带有json.loads() 的字典。之后,我将这个字典中的一些元素循环写入文件:
parsedJSON = json.loads(cleanJSON)
for i in range(len(parsedJSON['list'])):
f.write(html.unescape(parsedJSON['list'][i][4]) + ' - ' + html.unescape(parsedJSON['list'][i][3]) + '\n')
问题在于 JSON 可以包含日文/中文象形文字和其他特殊符号。在 JSON 字符串中,我将它们存储为 html 实体(例如,此字符串 '&# 12493;&# 12467;&# 12496;&# 12473;' 是ネコバス)。
要将 html 实体转换为人类可读的形式,我使用html.unescape('someHTMLEntity')。在我的 Debian 8 和其他一些 linux 系统上,它运行良好 - 象形文字代码被转换为实际的象形文字等。但在 Windows(7、8.1 和 10 上)我收到此错误:
Traceback (most recent call last):
File "main.py", line 144, in <module>
f.write(html.unescape(parsedJSON['list'][i][4]) + ' - ' + html.unescape(par
sedJSON['list'][i][3]) + '\n')
File "C:\Users\dangerous\AppData\Local\Programs\Python\Python36-32\lib\encodin
gs\cp1251.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 12-15: c
haracter maps to <undefined>
执行html.unescape('someHieroglyphCode')函数时程序崩溃。
据我了解,这是一些特定于 Windows 的编码问题,但我不明白究竟是什么。
【问题讨论】:
标签: python python-3.x encoding html-entities html-encode