【问题标题】:Extracting XML Element and Attribute Data with Python 3使用 Python 3 提取 XML 元素和属性数据
【发布时间】:2013-06-14 14:33:42
【问题描述】:

我希望使用 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 也是如此。我不确定我需要使用哪些库,是否存在此类库以及如果存在如何使用它们。

【问题讨论】:

    标签: python xml python-3.x lxml


    【解决方案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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多