【发布时间】:2014-07-21 15:47:14
【问题描述】:
我正在尝试使用 ElementTree 使用 Python 2.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>
上面的代码有多个问题,我想解决:
- Unicode 字符
Š没有被这段代码很好地消化。编辑:这已解决,部分原因是文件编码错误。 - 我想避免在文件名中使用特殊字符,例如空格和冒号。预处理这些的最佳方法是什么?我根据Remove all special characters, punctuation and spaces from string 和Convert a Unicode string to a string in Python (containing extra symbols) 的答案构建了一个
normalize函数。这是一种可行的方法吗? - 假设每个
element都有一个名为value的条目,element.find('value').text是访问存储在 xml 文档中的值的最佳方式吗?
【问题讨论】:
标签: xml python-2.7 unicode elementtree