【问题标题】:Extract text between tags containing a given word using Python使用 Python 提取包含给定单词的标签之间的文本
【发布时间】:2019-01-24 16:29:14
【问题描述】:

我有一些来自 XML 文档的文本,我试图在其中提取包含某些单词的标签中的文本。

例如:

search('adverse')

应该返回包含单词'adverse'的所有标签的文本

Out: 
  [
    "<item>The most common adverse reactions reported in subjects receiving coadministered dutasteride and tamsulosin were impotence, decreased libido, breast disorders (including breast enlargement and tenderness), ejaculation disorders, and dizziness.</item>"
  ]

search('clinical')

应该返回两个结果,因为两个标签包含这些词。

Out: 
  [
    "<title>6.1 Clinical Trials Experience</title>", 
    "<paragraph id="ID41">The clinical efficacy and safety of coadministered dutasteride and tamsulosin, which are individual components of dutasteride and tamsulosin hydrochloride capsules, have been evaluated in a multicenter, randomized, double-blind, parallel group trial (the Combination with Alpha-Blocker Therapy, or CombAT, trial) </paragraph>"
  ]

为此我应该使用什么工具?正则表达式? BS4?非常感谢任何建议。


示例文本:

 </highlight>
 </excerpt>
 <component>
 <section id="ID40">
 <id root="fbc21d1a-2fb2-47b1-ac53-f84ed1428bb4"></id>
 <title>6.1 Clinical Trials Experience</title>
 <text>
 <paragraph id="ID41">The clinical efficacy and safety of coadministered dutasteride and tamsulosin, which are individual components of dutasteride and tamsulosin hydrochloride capsules, have been evaluated in a multicenter, randomized, double-blind, parallel group trial (the Combination with Alpha-Blocker Therapy, or CombAT, trial) </paragraph>
 <list id="ID42" listtype="unordered" stylecode="Disc">
 <item>The most common adverse reactions reported in subjects receiving coadministered dutasteride and tamsulosin were impotence, decreased libido, breast disorders (including breast enlargement and tenderness), ejaculation disorders, and dizziness.</item>

【问题讨论】:

    标签: python xml nlp


    【解决方案1】:

    您可以使用正则表达式对其进行硬编码,也可以使用 lxml 之类的库来解析您的 xml 文件

    使用正则表达式:

    import re
    
    your_text = "(...)"
    
    def search(instr):
        return re.findall(r"<.+>.*{}.*<.+>".format(instr), your_text, re.MULTILINE)
    
    print(search("safety"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2016-03-27
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多