2013-05-03 89 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