【问题标题】:Python/LXML - Getting "grandchildren" from etreePython/LXML - 从 etree 获取“孙子”
【发布时间】:2013-05-03 19:14:27
【问题描述】:

这是我正在遍历的 XML 树的示例:

<entry dataset="Swiss-Prot" created="1993-07-01+01:00" modified="2013-04-03+01:00" version="144">
  <accession>P31750</accession>
  <accession>Q62274</accession>
  <accession>Q6GSA6</accession>
  <name>AKT1_MOUSE</name>
  <protein>
    <recommendedName>
      <fullName>RAC-alpha serine/threonine-protein kinase</fullName>
      <ecNumber>2.7.11.1</ecNumber>
    </recommendedName>
    <alternativeName>
      <fullName>AKT1 kinase</fullName>
    </alternativeName><alternativeName>
      <fullName>Protein kinase B</fullName>
     ..........

我正在尝试访问recommendedName,这是我用来访问它的当前Python 代码:

protein = e.find("{http://uniprot.org/uniprot}protein")
r_names = []
for child in protein.find("recommendedName"):
     for subchild in child.find("fullName"):
          r_names.append(subchild.text)

e 在此上下文中表示从 &lt;entry&gt;&lt;/entry&gt;。当我尝试运行此代码时,我从 Python 解释器收到以下错误:

for child in protein.find("recommendedName"):
  TypeError: 'NoneType' object is not iterable

所以它告诉我 child 这里不是一个可迭代的对象。我真的不明白,因为protein 绝对是可迭代的,所以如果它是finds 它应该是可迭代的。无论如何,我将如何使用lxml API 来访问孙节点recommendedNamealternativeName

【问题讨论】:

    标签: python python-3.x lxml elementtree


    【解决方案1】:
    for child in protein.find("recommendedName"):
      TypeError: 'NoneType' object is not iterable
    

    错误消息是说protein.find 正在返回None。所以没有找到recommendedName 元素。

    由于您使用命名空间来查找protein,因此您可能需要使用

    for child in protein.find("{http://uniprot.org/uniprot}recommendedName")
    

    或者更好,

    for child in protein.xpath("uniprot:recommendedName",
                               namespaces = dict(uniprot='http://uniprot.org/uniprot'))
    

    【讨论】:

    • 非常感谢,出于某种原因,我认为我只需要根目录、其子代及其兄弟姐妹的命名空间。我没有意识到我也可以将它用于嵌套元素。
    猜你喜欢
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2020-08-28
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多