【问题标题】:Encoding problems at the end of the execution执行结束时的编码问题
【发布时间】:2015-12-22 20:02:06
【问题描述】:

我的脚本有编码问题。这是我的脚本:

def parse_airfields():
    html = urlopen('https://www.sia.aviation-civile.gouv.fr/aip/enligne/FRANCE/AIRAC-2015-09-17/html/eAIP/FR-AD-1.3-fr-FR.html').read()
    html = html.decode('utf-8')
    soup = BeautifulSoup(html, 'lxml')
    
    # A lot of work [....]

    return airfields


if __name__ == '__main__':
    airfields = parse_airfields()

    for airfield in airfields:
        for value in airfield.values():
            if isinstance(value, str):
                value.encode('utf-8')

    with open('airfields.json', 'w') as airfields_file:
        json.dump(airfields, airfields_file, indent=4, sort_keys=True)

我尝试不使用encode() 和不使用decode(),但结果相同... JSON 文件中的编码问题:

为什么?感谢您的帮助!

【问题讨论】:

  • 什么问题?此外,调用encode() 方法的那一行会处理结果。

标签: python json python-3.x encoding beautifulsoup


【解决方案1】:

str.encodebytes.decode不要修改原地的值;您没有分配 value.encode('utf-8') 的返回值,因此您实际上没有更改任何内容。当然,我不认为你真的想这样做; json 模块适用于文本 (str),而不是二进制数据 (bytes)。

问题在于严格的 JSON 通常不会在其字符串中包含非 ASCII 字符;它使用转义符,例如\u00b0。如果你告诉它,Python 将直接输出utf-8,只需将ensure_ascii=False 添加到json.dump(...) 调用的参数中。

【讨论】:

  • 哇!那很完美!谢谢你的解释。祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2012-01-14
  • 2013-05-16
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多