91398


### 実現したいこと

`result.xml`という名のxmlファイルの **`<passage>`** の中のabstractの **`<text>`** の抽出をしたい.  
**`<text>`** の部分は, `Neurologic complications of COVID-19, ~ encephalopathy.`
の文と `The rapid evolution~replication.` の文を抽出したい.

ファイル: result.xml

[code]

    <collection>
      <document>
        <passage>
          <infon key="authors">Gupta NA, Lien C, Iv M, </infon>
          <offset>0</offset>
          <text>Critical illness-associated cerebral microbleeds in severe COVID-19 infection </text>
          <annotation id="5">
            <location offset="68" length="9" />
            <text>infection</text>
          </annotation>
        </passage>
        <passage>
          <infon key="section_type">ABSTRACT</infon>
          <infon key="type">abstract</infon>
          <offset>81</offset>
          <text>Neurologic complications of COVID-19 infection have been recently described and include dizziness, headache, loss of taste and smell, stroke, and encephalopathy.</text>
        </passage>
        <passage>
          <infon key="section_type">ABSTRACT</infon>
          <infon key="type">abstract_title_1</infon>
          <offset>584</offset>
          <text>Highlights</text>
        </passage>
      </document>
      <document>
        <passage>
          <infon key="name_4">surname:Ansari;given-names:M. Azim</infon>
          <offset>0</offset>
          <text>Extensive C->U transition biases in the genomes of a wide range of mammalian RNA viruses; potential associations with transcriptional mutations, damage- or host-mediated editing of viral RNA</text>
          <annotation id="1">
            <infon key="identifier">9606</infon>
            <infon key="type">Species</infon>
            <location offset="67" length="9" />
            <text>mammalian</text>
          </annotation>
        </passage>
        <passage>
          <infon key="type">abstract</infon>
          <offset>191</offset>
          <text>The rapid evolution of RNA viruses SARS-CoV-2 has been long considered to result from a combination of high copying error frequencies during RNA replication. </text>
        </passage>
        <passage>
          <infon key="section_type">ABSTRACT</infon>
          <infon key="type">abstract_title_1</infon>
          <offset>2033</offset>
          <text>Author summary</text>
        </passage>
      </document>
    </collection>
    
[/code]

スクリプト: 1.py

[code]

    from bs4 import BeautifulSoup
    with open('result.xml') as xml:
        soup = BeautifulSoup(xml, 'xml')
    
    result = []
    
    for passage in soup.find_all('passage'):
        text = passage.text
        if text and ('COVID-19' in text or 'SARS-CoV-2' in text):
            for line in text.splitlines():
                if line.strip().endswith('.'):
                    result3.append(line)
    
    print(*result,sep='^\n')
    
[/code]


CC BY-SA 4.0
2022-10-02T06:44:27.993
91397
2022-10-04T08:18:47.800
2022-10-04T08:18:47.800
3060
54656
question
python python3 xml
pythonでxmlファイルの一部分の情報を抽出したい


BeautifulSoupを利用します．

[code]

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(xml, 'xml')
    
    result = []
    
    for passage in soup.find_all('passage'):
        text = passage.text
        if text and ('COVID-19' in text or 'SARS-CoV-2' in text):
            for line in text.splitlines():
                if line.strip().endswith('.'):
                    result.append(line)
    
    print(*result, sep='\n')
    
    # Neurologic complications of COVID-19 infection have been recently described and include dizziness, headache, loss of taste and smell, stroke, and encephalopathy.
    # The rapid evolution of RNA viruses SARS-CoV-2 has been long considered to result from a combination of high copying error frequencies during RNA replication. 
    
[/code]

### 補足

  * 行末がピリオドで終わるものを文としました(その際前後の空白を除去しています)．
  * (追記)`if text and (...`について，textがNoneの場合(passageにtextタグが含まれていなかった場合)に次の`test in ...`でエラーを吐くことを防ぐ目的で，短絡評価を利用しています．


CC BY-SA 4.0
2022-10-02T07:31:19.033
91398
2022-10-02T10:41:18.873
2022-10-02T10:41:18.873
51374
51374
91397
answer


BeautifulSoup で CSS セレクタを使う場合。

[code]

    from bs4 import BeautifulSoup
    
    with open('result.xml') as xml:
        soup = BeautifulSoup(xml, 'xml')
    
    texts = soup.select('''
      passage >
      infon[key="type"]:-soup-contains("abstract"):not(:-soup-contains("_title")) ~
      text:-soup-contains("COVID-19", "SARS-CoV-2")
    ''')
    text = [t.text for t in texts]
    
    print('\n'.join(text))
    
    #
    Neurologic complications of COVID-19 infection have been recently described and include dizziness, headache, loss of taste and smell, stroke, and encephalopathy.
    The rapid evolution of RNA viruses SARS-CoV-2 has been long considered to result from a combination of high copying error frequencies during RNA replication. 
    
[/code]


CC BY-SA 4.0
2022-10-02T15:28:13.600
91404
2022-10-02T15:28:13.600
47127
91397
answer