字典关键字:valu

2024-06-16 10:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

值在键:值对列一张单子?我正试图找到一种有效解析大型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> 

其中可以有任意数量的“things”元素,每个元素可以有任意数量的“node”元素。节点元素包含体素坐标。我想知道哪个物体的体素对和其他物体的体素对相近。e、 物体1节点7是否靠近物体5节点8?我不想费心去确定同一事物中节点的接近程度(例如,我不想找出物1节点1是否靠近物1节点9;“边”数据负责这一点)。你知道吗

目前,我将所有数据转储到一个大列表中,并使用一组for循环和if语句遍历该列表。它工作正常,但速度很慢,部分原因是它逐点移动并不断查询被比较的两个节点是否在同一事物中。我认为使用字典结构会加快速度,但我对这一点还不熟悉。你知道吗

谢谢。你知道吗


Tags: idnode元素sourcetarget节点comment物体
1条回答
网友
1楼 · 发布于 2024-06-16 10:19:32

可以从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'}

相关问题 更多 >