我希望使用 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 时更是如此。我不确定我需要使用哪些库,如果存在此类库,也不确定如何使用它们。
最佳答案
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']
关于python - 使用 Python 3 提取 XML 元素和属性数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17110929/