Python/LXML子节点返回“NoneType”

2024-09-27 09:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我正在遍历的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>
    <alternativeName>
      <fullName>Some other value</fullName>
    </alternativeName><alternativeName>
     ..........

我正试着去alternativeName。我在获取recommended name时没有任何问题,因此我尝试使用alternativeName的相同方法。但是,Python解释程序输出以下错误消息:

^{pr2}$

下面是我用来获取这些元素的Python代码。同样,代码对于recommendedName工作良好,但对于alternativeName则不行。谢谢你的帮助!在

alt_shortnames = []
alt_fullnames = []

protein = e.find("{http://uniprot.org/uniprot}protein")
for child in protein.find("{http://uniprot.org/uniprot}alternativeName"):
    if child.tag == "{http://uniprot.org/uniprot}fullName":
        alt_fullnames.append(child.text)
    if child.tag == "{http://uniprot.org/uniprot}shortName":
        alt_shortnames.append(child.text)

temp_dict["alternativeFullNames"] = alt_fullnames
temp_dict["alternativeShortNames"] = alt_shortnames

Tags: nameorgchildhttpaltuniprotfullnameprotein
1条回答
网友
1楼 · 发布于 2024-09-27 09:29:59

您使用的是protein.find()^{} method返回找到的元素,或者返回{}(如果没有找到任何内容)。在

如果希望找到元素的序列,请使用^{}。该方法始终返回iterable(可能为空):

for altName in protein.findall("{http://uniprot.org/uniprot}alternativeName"):
    for child in altName:
        if child.tag == "{http://uniprot.org/uniprot}fullName":
            alt_fullnames.append(child.text)
        if child.tag == "{http://uniprot.org/uniprot}shortName":
            alt_shortnames.append(child.text)

相关问题 更多 >

    热门问题