【问题标题】:Reading emojis from an XML file using Python使用 Python 从 XML 文件中读取表情符号
【发布时间】:2017-08-03 01:43:10
【问题描述】:

我正在尝试从this XML 文件中读取表情符号。手动复制它们是可行的,它们可以打印出来,并且仍然可以在浏览器中正确显示。

import requests
import xml.etree.ElementTree as ET

root = ET.fromstring(requests.get('http://www.unicode.org/repos/cldr/trunk/common/annotations/en.xml').text)

print(root[1][21].attrib['cp'])

这应该会获取“笑眼笑脸”????
bytes(????, 'utf-8') 返回:b'\xf0\x9f\x98\x84'。 但是使用上面的代码获取会产生 'ð\x9f\x98\x84'。
在 XML 解析器中有什么需要做的吗?

【问题讨论】:

    标签: python xml python-requests


    【解决方案1】:

    Response.text 将解码内容(参见http://docs.python-requests.org/en/master/user/quickstart/#response-content)。 ElementTree 再次解码已经解码的字节(基于<?xml version="1.0" encoding="UTF-8" ?>)。

    尝试Response.content 将未修改的响应传递给ElementTree

    import requests
    import xml.etree.ElementTree as ET
    
    root = ET.fromstring(requests.get('http://www.unicode.org/repos/cldr/trunk/common/annotations/en.xml').content)
    
    print(root[1][21].attrib['cp'])
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 2017-11-12
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多