【问题标题】:How to extract multiple citations separated by tags from a text using regular expression?如何使用正则表达式从文本中提取由标签分隔的多个引用?
【发布时间】:2017-06-14 12:33:04
【问题描述】:

我有一个手动输入文件,其中包含引文,每个文件的格式为:

和以前的机器不同 基于学习的NER,因为它使用来自整体的信息 文档对每个单词进行分类,只有一个分类器。以前涉及从整个文档中收集信息的工作通常使用二级分类器, 它纠正了基于句子的主要分类器的错误。

这是我目前使用 python 的 re 模块的方法:

citance = citance[citance.find(">")+1:citance.rfind("<")]
fd.write(citance+"\n")

我试图提取从第一个右尖括号 (">") 到最后一个左尖括号 ("

它与以前基于机器学习的 NER 不同之处在于它使用 来自整个文档的信息来对每个单词进行分类,只需 一个分类器。以前的工作涉及到 从整个文档中收集信息通常使用 二级分类器,纠正初级分类器的错误 基于句子的分类器。

我想要的输出:

它与以前基于机器学习的 NER 不同之处在于它使用 来自整个文档的信息来对每个单词进行分类,只需 一个分类器。以前的工作涉及 从整个文档中收集信息通常使用 二级分类器,纠正初级分类器的错误 基于句子的分类器。

我怎样才能正确地实现它?

【问题讨论】:

    标签: python regex python-3.x citations


    【解决方案1】:

    我会使用 python 正则表达式模块:re 通过这样做:

    re.findall(r'\">(.*?)<', text_to_parse)
    

    这个方法会从一个引号返回到多个引号,但是如果你想要一个统一的文本你可以加入它们之后(" ".join(....)

    【讨论】:

      【解决方案2】:

      不要使用 re 模块,而是查看 bs4 库。

      这是一个 XML/HTML 解析器,因此您可以获取标签之间的所有内容。

      对你来说,它会是这样的:

      from bs4 import BeautifulSoup
      
      xml_text = '< S sid ="2" ssid = "2">It differs from previous machine learning-based NERs in that it uses information from the whole document to classify each word, with just one classifier.< /S>< S sid ="3" ssid = "3">Previous work that involves the gathering of information from the whole document often uses a secondary classifier, which corrects the mistakes of a primary sentence- based classifier.< /S>'
      
      text_soup = BeautifulSoup(xml_text, 'lxml')
      
      output = text_soup.find_all('S', attrs = {'sid': '2'})
      

      输出将包含文本:

      它与以前基于机器学习的 NER 不同之处在于,它使用整个文档中的信息对每个单词进行分类,只使用一个分类器。

      此外,如果您只想删除 html 标签:

      import re
      
      xml_text = '< S sid ="2" ssid = "2">It differs from previous machine learning-based NERs in that it uses information from the whole document to classify each word, with just one classifier.< /S>< S sid ="3" ssid = "3">Previous work that involves the gathering of information from the whole document often uses a secondary classifier, which corrects the mistakes of a primary sentence- based classifier.< /S>'
      
      re.sub('<.*?>', '', html_text)
      

      会做的。

      【讨论】:

        【解决方案3】:

        我想这就是你要找的。​​p>

        import re
        
        string = ">here is some text<>here is some more text<"
        matches = re.findall(">(.*?)<", string)
        for match in matches: print match
        

        您在获取太多结果时似乎遇到了问题。 “here is some more text”和“

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-05-08
          • 1970-01-01
          • 2020-06-08
          • 1970-01-01
          • 2017-02-25
          • 2023-03-28
          • 2012-06-15
          相关资源
          最近更新 更多