使用Python中的xml.etree.ElementT遍历XML树存在问题

2024-06-28 19:21:49 发布

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

我有一个XML文件,其结构如下所示(为解决此问题而简化)。对于每个记录,我想提取文章标题和包含“ArticleId”元素中的DOI编号的属性“IdType”的值(有时该属性可能会丢失),然后将文章标题存储在以DOI为键的字典中

<PubmedArticleSet>
<PubmedArticle>
    <MedlineCitation Status="MEDLINE" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>Malathion and dithane induce DNA damage in Vicia faba.</ArticleTitle>
        </Article>
    </MedlineCitation>  
    <PubmedData>
        <ArticleIdList>
            <ArticleId IdType="pubmed">28950791</ArticleId>
            <ArticleId IdType="doi">10.1177/0748233717726877</ArticleId>
        </ArticleIdList>
    </PubmedData>
</PubmedArticle>

<PubmedArticle>
    <MedlineCitation Status="MEDLINE" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.</ArticleTitle>
        </Article>
    </MedlineCitation>  
    <PubmedData>
        <ArticleIdList>
            <ArticleId IdType="pubmed">25747267</ArticleId>
            <ArticleId IdType="pii">S1631-0691(15)00050-5</ArticleId>
            <ArticleId IdType="doi">10.1016/j.crvi.2015.02.001</ArticleId>
        </ArticleIdList>
    </PubmedData>
</PubmedArticle>

<PubmedArticle>
    <MedlineCitation Status="MEDLINE" IndexingMethod="Curated" Owner="NLM">
        <Article PubModel="Print-Electronic">
            <ArticleTitle>[Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].</ArticleTitle>
        </Article>
    </MedlineCitation>
    <PubmedData>
    <ArticleIdList>
        <ArticleId IdType="pubmed">27548984</ArticleId>
        <!-- in this record, DOI is missing -->
    </ArticleIdList>
    </PubmedData>
</PubmedArticle>
</PubmedArticleSet>

为了实现这一目标,我使用了xml.etree.ElementTree,如下所示:

import xml.etree.ElementTree as ET

xmldoc = ET.parse('sample.xml')
root = xmldoc.getroot()
pubs = {}
for elem in xmldoc.iter(tag='ArticleTitle'):
    title = elem.text
    for subelem in xmldoc.iter(tag='ArticleId'):
        if subelem.get("IdType") == "doi":
            doi = subelem.text 
            pubs[doi] = title

if len(pubs) == 0:
   print "No articles found"
else:   
   for pub in pubs.keys():
       print pub + ' ' + pubs[pub]

但是遍历文档树的循环有一个问题,因为上面的代码导致:

10.1177/0748233717726877 [Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].
10.1016/j.crvi.2015.02.001 [Influence of Four Kinds of PPCPs on Micronucleus Rate of the Root-Tip Cells of Vicia-faba and Garlic].

也就是说,我得到了正确的DOI,但只是上一篇文章标题的副本,没有DOI

正确的输出应为:

10.1177/0748233717726877 Malathion and dithane induce DNA damage in Vicia faba.
10.1016/j.crvi.2015.02.001 Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.

有谁能给我一些提示来解决这个烦人的问题吗


Tags: andofinarticledoiarticleididtypemedlinecitation
1条回答
网友
1楼 · 发布于 2024-06-28 19:21:49

这是根本错误的:

for elem in xmldoc.iter(tag='ArticleTitle'):      # <  *ALL* <ArticleTitle> elements
    ...
    for subelem in xmldoc.iter(tag='ArticleId'):  # <  *ALL* <ArticleId> elements
        ...

ElementTree中没有只选择与您碰巧看到的最后一个<ArticleTitle>相关联的<ArticleId>的读心术,因此您发现的与该代码相关的任何内容实际上都没有关系

围绕实际的XML文档(“针对每个PubmedArticle…”)构建代码,并使用相对搜索:

pubs = []

for pubmedArticle in xmldoc.iter(tag='PubmedArticle'):  
    # relative search within this <PubmedArticle>
    articleTitle = pubmedArticle.find('./MedlineCitation/Article/ArticleTitle')

    # always verify that there are actual results for a search
    if articleTitle == None:
       title = "No article title found"
    else:
       title = articleTitle.text

    for articleId in pubmedArticle.iterfind('./PubmedData//ArticleId'):
        if articleId.get("IdType") == "doi":
            pubs.append({"doi": articleId.text, "title": title})

我还建议您列出一个dict列表,而不是一个dict。使用以下代码将更容易处理:

[
    {'doi': '10.1177/0748233717726877', 'title': 'Malathion and dithane induce DNA damage in Vicia faba.'},
    {'doi': '10.1016/j.crvi.2015.02.001', 'title': 'Impact of dual inoculation with Rhizobium and PGPR on growth and antioxidant status of Vicia faba L. under copper stress.'}
]

相关问题 更多 >