2013-05-03 92 views
0

这里是XML树,我穿越的样本:的Python/LXML - 儿童节点返回“NoneType”

<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解释器将输出以下错误信息:

for child in protein.find("{http://uniprot.org/uniprot}alternativeName"): 
TypeError: 'NoneType' object is not iterable 

这里是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 
+0

您需要验证*为什么*替代名称没有被找到。在“蛋白质”儿童的交互式会话中迭代,看看有哪些标签。你确定'alternativeName'标签是*永远存在吗?难道它有时不在吗?如果是,请测试'无',如果无法使用则继续。 – 2013-05-03 21:55:30

+0

你的其他答案发生了什么?我相信这是正确的,我需要使用'findall'而不是'find'。它似乎现在工作。添加答案,我会接受它。 – Houdini 2013-05-03 22:00:36

+0

另外,感谢您的额外帮助! – Houdini 2013-05-03 22:01:15

回答

1

您正在使用protein.find();如果找不到任何内容,则.find() method返回找到的元素或None

如果您希望找到序列的元素,请使用.findall()。该方法总是返回一个可迭代(可能为空):

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) 
+0

我认为OP故意尝试遍历找到的元素以获取其子元素。也许我太困了,虽然 – 2013-05-03 21:47:26

+0

@LevLevitsky:啊,我明白你的意思了。 – 2013-05-03 21:54:01

+0

您的解决方案确实允许解析完成。对于这些列表,我仍然有空的值,所以别的东西一定是错的。但是使用'findall'至少允许解析器传递整个文档。 – Houdini 2013-05-03 22:10:30