Skip to main content
 首页 » 编程设计

Python UTF-8 编码问题

2024年10月17日8kevingrace

在从网站解析 xml 的过程中,我设法迷失在一堆 utf-8 编码问题中。具体来说,我的字符串如下所示:

u'PA_g\xc3\xa9p7' 

当我打印这个时,我得到:

>> PA_gép7 

我想要的不是来自以下内容

print('PA_g\xc3\xa9p7') 
>> PA_gép7 

这是我的代码:

def get_api_xml_response(base_url, query_str): 
"""gets xml from api @ base_url using query_str""" 
  res = requests.get(u'{}{}'.format(base_url, query_str)) 
  xmlstring = clean_up_xml(res.content).encode(u'utf-8') 
  return ET.XML(xmlstring) 

我的函数 clean_up_xml 的存在是为了删除导致我出现问题的 namespace 和其他字符。

def clean_up_xml(xml_string): 
"""remove the namespace and invalid chars from an xml-string""" 
   return re.sub(' xmlns="[^"]+"', '', xml_string, count=1).replace('&', '&') 

请您参考如下方法:

您从 res.content 中获取一个以/most probably/UTF-8 编码的二进制字符串,并将其再次编码为 UTF-8。二进制字符串应该只被decode()'d,Unicode 字符串应该只被encode()'d,除了一些special cases .

由于 clean_up_xml() 使用二进制字符串,最好将二进制输入传递给 ElementTree,它会正确处理:

xmlstring = clean_up_xml(res.content) 
# let ElementTree decode content using information from the XML itself 
# e.g. <?xml version="1.0" encoding="UTF-8"?> 
return ET.XML(xmlstring) 

如果您决定重构代码以使用 unicode,则应尽快解码所有二进制输入:

# let requests decode response using information from HTTP header 
# e.g. Content-Type: text/xml; charset=utf-16 
xmlstring = clean_up_xml(res.text) 
return ET.XML(xmlstring) 

当询问与 Unicode 相关的问题时,指定 Python 版本很重要,在本例中是从 future 导入的带有 print_function 的 Python 2。在 Python 3 中,您会看到以下内容:

>>> print('PA_g\xc3\xa9p7') 
PA_gép7 
>>> 'PA_g\xc3\xa9p7' == u'PA_g\xc3\xa9p7' 
True