在Python2.7中读取包含unicode的XML文件

在Python2.7中读取包含unicode的XML文件,xml,python-2.7,unicode,elementtree,Xml,Python 2.7,Unicode,Elementtree,我正在尝试使用带有ElementTree的Python2.7.6解析来自某个服务器的unicode编码的xml文件,并将包含的数据保存在本地 import xml.etree.ElementTree as ET def normalize(string): if isinstance(string, unicode): normalized_string = unicodedata.normalize('NFKD', string).encode('ascii','

我正在尝试使用带有ElementTree的Python2.7.6解析来自某个服务器的unicode编码的xml文件,并将包含的数据保存在本地

import xml.etree.ElementTree as ET

def normalize(string):
    if isinstance(string, unicode): 
        normalized_string  = unicodedata.normalize('NFKD', string).encode('ascii','ignore')
    elif isinstance(string, str):
        normalized_string  = string
    else:
        print "no string"
        normalized_string  = string

    normalized_string  = ''.join(e for e in normalized_string if e.isalnum())
    return normalized_string

tree = ET.parse('test.xml')
root = tree.getroot()

for element in root:
    value = element.find('value').text
    filename = normalize(element.find('name').text.encode('utf-8')) + '.txt'
    target = open(filename, 'a')
    target.write(value + '\n')
    target.close()
我正在解析的文件的结构类似于以下内容,我已将其保存为本地的
test.xml

<data> 
<product><name>Something with a space</name><value>10</value> </product>
<product><name>Jakub Šlemr</name><value>12</value></product>
<product><name>Something with: a colon</name><value>11</value></product>
</data>

有空格的东西
雅库布·什勒姆12
有:冒号11的东西
上面的代码有多个问题,我想解决:

  • unicode字符
    Š
    未被该代码很好地消化。编辑:这已经解决了,部分原因是文件编码错误
  • 我希望避免在文件名中使用特殊字符,例如空格和冒号。最好的预处理方法是什么?我基于和的答案构建了一个
    规范化
    函数。这种方法行吗
  • element.find('value')。text
    是访问xml文档中存储的值的最佳方式,假设每个
    元素
    都有一个名为
    value
    的条目

  • 元素中的值。查找('value')。文本是unicode对象。当您将它们与ascii字符串对象(如
    '.txt'
    )一起追加时,它们将与所需的转换一起连接

    在序列化unicode对象之前,不能打印或存储它们。如果不显式地这样做,Python将使用默认编码设置隐式地这样做。默认编码是ASCII,它只支持非常有限的字符集,导致任何输入数据包含非ASCII字符时出现
    UnicodeEncodeError

    我建议您使用适合您的解决方案的编解码器,使用
    encode()
    方法将unicode对象显式编码为字符串。例如,如果要将文本元素编码为
    UTF-8
    encoded字符串,请调用:

    element.find('value').text.encode('utf-8')
    

    另外,检查XML中的编码属性是否设置正确。错误的编码很可能是导致解析错误的原因。

    几乎不值得注意的是,
    'name'
    是有问题的标记,而不是
    'value'
    。因为我想规范化名称,使其不包含冒号等;我引入了一个函数,它将名称规范化为字母数字ascii-在这种情况下,我需要显式编码吗?还有:是的,文件编码确实关闭了。这个答案是错误的。在Python2.7中连接Unicode和字符串时,它会将字符串上转换为Unicode;它不会将Unicode下变频为ascii。