【问题标题】:Parse xml in Python 3.x在 Python 3.x 中解析 xml
【发布时间】:2019-04-24 08:27:24
【问题描述】:

我有一些想要解析的 xml 代码。我希望使用 ElementTree 而不是 BeautifulSoup,因为后者处理 xml 的方式存在一些问题。

我希望从以下内容中提取文本:

  • 抽象/抽象文本
  • ArticleId 当 IdType="pmc"
  • 在检索相应的文本之前,首先检索具有“UI”值的PublicationType

我使用 ElementTree 的哪些功能来完成这项工作?

我一直在尝试使用.attrib、attrib.get()、.iter、.attrib[key] 来获取文本,但我没有成功访问实际文本。

<PubmedArticleSet>
   <PubmedArticle>
       <PMID Version="1">10890875</PMID>
       <Journal>
           <ISSN IssnType="Print">0143-005X</ISSN>
            <Title>Journal of epidemiology and community health</Title>
       </Journal>
       <ArticleTitle>Sources of influence on medical practice. 
       </ArticleTitle>
       <Abstract>
          <AbstractText Label="OBJECTIVES" NlmCategory="OBJECTIVE">
             To explore the opinion of general practitioners on the 
             importance and legitimacy of sources of influence on 
             medical practice.
          </AbstractText>
          <AbstractText Label="METHODS" NlmCategory="METHODS">
             General practitioners (n=723) assigned to Primary Care 
             Teams (PCTs) in two Spanish regions were randomly selected 
             to participate in this study. 
          </AbstractText>
          <AbstractText Label="RESULTS" NlmCategory="RESULTS">
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues. 
          </AbstractText>
          <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting. </AbstractText>
        </Abstract>
        <Language>eng</Language>
        <PublicationTypeList>
           <PublicationType UI="D016428">Journal Article 
           </PublicationType>
           <PublicationType UI="D013485">Research Support, Non-U.S.Gov't </PublicationType>
        </PublicationTypeList>
    <PubmedData>
         <PublicationStatus>ppublish</PublicationStatus>
         <ArticleIdList>
            <ArticleId IdType="pubmed">10890875</ArticleId>
            <ArticleId IdType="pmc">PMC1731730</ArticleId>
         </ArticleIdList>
     </PubmedData>
   </PubmedArticle>
</PubmedArticleSet>

我希望得到的结果是: 生成 AbstractText 的每个“标签” 获取该“标签”的文本

【问题讨论】:

  • 您能否添加一个您想要的输出示例?

标签: xml python-3.x beautifulsoup elementtree


【解决方案1】:

使用 Css 选择器尝试以下代码。

from bs4 import BeautifulSoup

html='''<PubmedArticleSet>
   <PubmedArticle>
       <PMID Version="1">10890875</PMID>
       <Journal>
           <ISSN IssnType="Print">0143-005X</ISSN>
            <Title>Journal of epidemiology and community health</Title>
       </Journal>
       <ArticleTitle>Sources of influence on medical practice. 
       </ArticleTitle>
       <Abstract>
          <AbstractText Label="OBJECTIVES" NlmCategory="OBJECTIVE">
             To explore the opinion of general practitioners on the 
             importance and legitimacy of sources of influence on 
             medical practice.
          </AbstractText>
          <AbstractText Label="METHODS" NlmCategory="METHODS">
             General practitioners (n=723) assigned to Primary Care 
             Teams (PCTs) in two Spanish regions were randomly selected 
             to participate in this study. 
          </AbstractText>
          <AbstractText Label="RESULTS" NlmCategory="RESULTS">
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues. 
          </AbstractText>
          <AbstractText Label="CONCLUSIONS" NlmCategory="CONCLUSIONS">
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting. </AbstractText>
        </Abstract>
        <Language>eng</Language>
        <PublicationTypeList>
           <PublicationType UI="D016428">Journal Article 
           </PublicationType>
           <PublicationType UI="D013485">Research Support, Non-U.S.Gov't </PublicationType>
        </PublicationTypeList>
    <PubmedData>
         <PublicationStatus>ppublish</PublicationStatus>
         <ArticleIdList>
            <ArticleId IdType="pubmed">10890875</ArticleId>
            <ArticleId IdType="pmc">PMC1731730</ArticleId>
         </ArticleIdList>
     </PubmedData>
   </PubmedArticle>
</PubmedArticleSet>'''

soup = BeautifulSoup(html, 'lxml')

maintag=soup.select_one('Abstract')
for childtag in maintag.select('AbstractText'):
    print(childtag.text.strip())

print(soup.select_one('ArticleId[IdType="pmc"]').text)

输出:

To explore the opinion of general practitioners on the 
             importance and legitimacy of sources of influence on 
             medical practice.
General practitioners (n=723) assigned to Primary Care 
             Teams (PCTs) in two Spanish regions were randomly selected 
             to participate in this study.
The most important and legitimate sources of influence according to general practitioners were: training courses and scientific articles, designing self developed protocols and discussing with colleagues.
The development of medical practice is determined by many factors, grouped around three big areas: organisational setting, professional system and social setting.
PMC1731730

【讨论】:

    【解决方案2】:

    一般来说,我已经很好地使用了 .find() 方法来查看已用 ElementTree 解析的 XML 文件。然后,无论你找到什么,你都可以使用 element.text、element.attrib 和 element.tag 来分别获取文本、属性字典和元素名称。

    将它与列表理解结合起来,听起来这就是您要寻找的东西。

    例如,假设您将 xml 文件保存为“publications.xml”:

    import xml.etree.ElementTree as ET
    
    filename = 'publications.xml'
    content = ET.parse(filename)
    root = content.getroot()
    
    abstracts = [a.text for a in root.find('PubmedArticle/Abstract')]
    

    将为您提供 4 个摘要中的文本列表。

    可以通过类似的方式访问所有 ID,添加对正确 IdType 的检查。通过上面提到的方法,您可以类似地获取名称为'ArticleId'的所有元素的列表,然后使用

    element.attrib['IdType']
    

    对于给定列表中的每个元素。

    对于最后一个请求,我不完全确定您首先检索 UI 值是什么意思。如果您只想确保检索这两个值,则可以遍历

    中的所有元素
    root.find('PubmedArticle/PublicationTypeList')
    

    并保存 element.attrib['UI'] 和 element.text

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2023-02-21
      • 1970-01-01
      相关资源
      最近更新 更多