键:值对中的值可以是列表吗?我正在尝试找出一种高效地解析大型XML文件的方法。一般格式为:
<things>
<parameters>
<various parameters>
</parameters>
<thing id="1" comment="thing1">
<nodes>
<node id="1" x="1" y="1" z="1"/>
<node id="2" x="2" y="2" z="2"/>
</nodes>
<edges>
<edge source="1" target="2"/>
</edges>
</thing>
<thing id="N" comment="thingN">
<nodes>
<node id="3" x="3" y="3" z="3"/>
<node id="4" x="4" y="4" z="4"/>
</nodes>
<edges>
<edge source="3" target="4"/>
</edges>
</thing>
<comments>
<comment node="1" content="interesting feature"/>
<comment node="4" content="interesting feature"/>
</comments>
</things> 其中可以有任意数量的“事物”元素,每个元素可以有任意数量的“节点”元素。节点元素包含体素坐标。我想知道哪些东西-体素对接近其他东西-体素对。例如,事物1的节点7是否接近事物5的节点8?我不想费心去确定同一事物中节点的接近度(例如,我不想知道事物1节点1是否靠近事物1节点9;“边”数据会处理这一点)。
目前,我将所有数据转储到一个大列表中,并使用一堆for循环和if语句遍历该列表。它可以工作,但速度很慢,部分原因是它逐点移动,并不断询问被比较的两个节点是否在同一事物中。我认为使用字典结构会加快速度,但我对此还是个新手。
谢谢。
发布于 2015-07-27 03:52:26
您可以从XML字符串创建ElementTree。
from xml.etree import ElementTree as ET
xml = """<note>
<to>Monti</to>
<from>Python</from>
<heading>Reminder</heading>
<body>Spam!</body>
</note>"""
tree = ET.fromstring(xml)然后你可以遍历你的树,我们使用字典理解来映射标签和文本。
>>> {c.tag: c.text for c in tree.getchildren()}
{'body': 'Spam!', 'from': 'Python', 'heading': 'Reminder', 'to': 'Monti'}https://stackoverflow.com/questions/31640715
复制相似问题