2

我希望使用 Python 3 从特定元素中提取特定属性的值。

有问题的元素示例(Atom3d):

<Atom3d ID="18" Mapping="43" Parent="2" Name="C7" 
XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39" 
TemperatureType="Isotropic" IsotropicTemperature="0.0677" 
AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/>

我需要提取 XYZ 值,还需要获取该值并将其中以逗号分隔的数字分开。我需要在另一个不同格式的输入文件中使用这些数字,所以我想将它们分配给三个单独的变量并从那里获取。

我对 Python 非常缺乏经验,在涉及 XML 时完全如此。我不确定我需要使用哪些库,如果这些库甚至存在,以及如果它们存在如何使用它们。

4

1 回答 1

1

http://docs.python.org/3/library/xml.etree.elementtree.html

>>> from xml.etree import ElementTree as ET
>>> elem = ET.fromstring('''<Atom3d ID="18" Mapping="43" Parent="2" Name="C7"
... XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39"
... TemperatureType="Isotropic" IsotropicTemperature="0.0677"
... AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/>
... ''')

使用 get('attribute-name') 获取属性:

>>> elem.get('XYZ')
'0.0148299997672439,0.283699989318848,1.0291999578476'

用 ',' 分割字符串:

>>> elem.get('XYZ').split(',')
['0.0148299997672439', '0.283699989318848', '1.0291999578476']
于 2013-06-14T15:13:06.423 回答