【问题标题】:Error while converting html entities to hieroglyphs/special symbols [python]将 html 实体转换为象形文字/特殊符号时出错 [python]
【发布时间】: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


    【解决方案1】:

    在 open() 中使用 utf-8 编码显式修复它:

    f = open('./dump', 'a', encoding='utf-8')
    

    【讨论】:

      猜你喜欢
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      相关资源
      最近更新 更多