Python - Elementtree - 使用变量在树中搜索
我有一个包含很多化学基团及其属性的xml文件。下面是这个文件的一部分:
<groups>
<group name='CH3'>
<mw>15.03502</mw>
<heatCapacity>
<a>19.5</a>
</heatCapacity>
</group>
<group name='CH2'>
<mw>14.02708</mw>
<heatCapacity>
<a>-0.909</a>
</heatCapacity>
</group>
<group name='COOH'>
<mw>45.02</mw>
<heatCapacity>
<a>-24.1</a>
</heatCapacity>
</heatCapacity>
</group>
<group name='OH'>
<mw>17.0073</mw>
<heatCapacity>
<a>25.7</a>
</heatCapacity>
</group>
<\groups>
在我的Python代码中,我使用ElementTree来解析这个文件。我有一个列表 blocks=['CH3','CH2'],我想用这个列表来找到这两个基团。我尝试了以下代码:
import elementtree.ElementTree as ET
document = ET.parse( 'groups.xml' )
blocks=['CH3','CH2']
for item in blocks:
group1 = document.find(item)
print group1
但是我得到的结果都是'None'。你能帮我一下吗?
非常感谢
2 个回答
2
试试这个:
for block in blocks:
group = document.find('./group[@name="{}"]'.format(block))
if group:
xml.etree.ElementTree.dump(group)
else:
print "Group {} not found.".format(group)
3
你可以通过一个元素的 .get()
方法来找到它的属性。这里有一种查看属性的方法:
import xml.etree.ElementTree as ET
document = ET.parse( 'groups.xml' )
blocks=['CH3','CH2']
for group in document.getroot():
if group.get('name') in blocks:
print group
如果你需要根据特定的选择条件来访问数据,你可以自己创建一个字典:
import xml.etree.ElementTree as ET
# Parse
document = ET.parse( 'groups.xml' )
# Add a dictionary so that <group>s
# are easy to find by name
groups = {}
for group in document.getroot():
groups[group.get('name')] = group
# Look up our compounds in the dictionary
blocks=['CH3', 'CH2']
for item in blocks:
group = groups[item]
mw = group.find('mw').text
print item, mw