我想解析 utf-8 中的 xml 文件并按某个字段对其进行排序。排序是由自定义字母(来自源代码的 s1)。问题的历史在这里: 排序包含 utf-8 charachters 的列表。我在这里找到了如何对 xml 进行排序。排序工作正常,问题出在 elementtree 上,我必须承认它在 python3 上不起作用
这是源代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#import xml.etree.ElementTree as ET # Python 2.5
import elementtree.ElementTree as ET
s1='aáàAâÂbBcCçÇdDeéEfFgGğĞhHiİîÎíīıIjJkKlLmMnNóoOöÖpPqQrRsSşŞtTuUûúÛüÜvVwWxXyYzZ'
s2='11111122334455666aabbccddeeeeeeffgghhiijjkklllllmmnnooppqqrrsssssttuuvvwwxxyy'
trans = str.maketrans(s1, s2)
def unikey(seq):
return seq[0].translate(trans)
tree = ET.parse("tosort.xml")
container = tree.find("entries")
data = []
for elem in container:
keyd = elem.findtext("k")
data.append((keyd, elem))
print (data)
data.sort(key=unikey)
print (data)
container[:] = [item[-1] for item in data]
tree.write("sorted.xml", encoding="utf-8")
以下是
导入 elementtree 模块的说明。当我以这种方式导入模块时 : import xml.etree.ElementTree as ET
,我收到一条消息:
Traceback (most recent call last):
File "pcs.py", line 19, in <module>
container[:] = [item[-1] for item in data]
File "/usr/lib/python3.1/xml/etree/ElementTree.py", line 210, in __setitem__
assert iselement(element)
AssertionError
当我使用此方法导入时:import elementtree.ElementTree as ET
,我收到此消息:
Traceback (most recent call last):
File "pcs.py", line 4, in <module>
import elementtree.ElementTree as ET
File "/usr/local/lib/python3.1/dist-packages/elementtree/ElementTree.py", line 794, in <module>
_escape = re.compile(eval(r'u"[&<>\"\u0080-\uffff]+"'))
File "<string>", line 1
u"[&<>\"\u0080-\uffff]+"
^
SyntaxError: invalid syntax
我使用 Python 3.1.3(r313:86834,2010 年 11 月 28 日,11:28:10)。在python2.6 elementtree 工作没有问题。
tosort.xml 的内容:
<xdxf>
<entries>
<ar><k>zaaaa</k>definition1</ar>
<ar><k>şaaaa</k>definition2</ar>
...
...
</entries>
</xdxf>