Python:基于Criteri从行正则表达式中提取句子

2024-09-27 21:28:41 发布

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

有点像python/编程新手。。。在

我正试图想出一个正则表达式,它可以处理从文本文件中的一行中提取句子,然后将它们附加到列表中。代码:

import re

txt_list = []

with open('sample.txt', 'r') as txt:
    patt = r'.*}[.!?]\s?\n?|.*}.+[.!?]\s?\n?'
    read_txt = txt.readlines()

    for line in read_txt:
        if line == "\n":
            txt_list.append("\n")
        else: 
            found = re.findall(patt, line)
            for f in found:
                txt_list.append(f)


for line in txt_list:
    if line == "\n":
        print "newline"
    else:
        print line

以上代码最后5行的打印输出:

^{pr2}$

'的内容示例.txt':

^{3}$

我已经玩了几个小时的正则表达式,我似乎无法破解它。就目前而言,regex在for lunch?结尾处不匹配。因此这两个句子What {will|shall|should} we {eat|have} for lunch? Peas by the {thousand|hundred|1000} said Dr. Munchauson; {that|is} what he said.没有分开;这就是我想要的。在

正则表达式的一些重要细节:

  • 每一句话都会以句号、感叹号或问号结尾
  • 每个句子都至少包含一对大括号{},并在其中添加一些单词。而且在每句话的最后一个括号后也不会有误导性的“.”。因此Dr.总是在每个句子最后一对花括号之前。这就是为什么我尝试使用'}'来建立我的正则表达式。这样我就可以避免使用异常方法,为Dr.Jr.approx.等语法创建异常。对于我运行这段代码的每个文件,我个人都要确保在任何句子的最后一个“}”后面没有“误导性句点”。在

我想要的输出是:

{Hello there|Hello|Howdy} Dr. Munchauson you {gentleman|fine fellow}! 
What {will|shall|should} we {eat|have} for lunch?
Peas by the {thousand|hundred|1000} said Dr. Munchauson; {that|is} what he said.

newline
I am the {very last|last} sentence for this {instance|example}.

Tags: the代码inretxtforreadline
2条回答

如果您不介意添加一个依赖项,那么NLTK库有一个sent_tokenize函数,它应该可以满足您的需要,尽管我不完全确定花括号是否会干涉。在

描述NLTK方法的论文长达40多页。检测句子边界并不是一件小事。在

我得到的最直观的解决方案是这个。本质上,您需要将Dr.Mr.标记本身视为原子。在

patt = r'(?:Dr\.|Mr\.|.)*?[.!?]\s?\n?'

它说:

Find me the least number of Mr.s, Dr.s or any character up to a puncuation mark followed by a zero or one spaces which is followed by zero or one new lines.

用在这个上面示例.txt(我加了一行):

^{pr2}$

它提供:

{Hello there|Hello|Howdy} Dr. Munchauson you {gentleman|fine fellow}!
What {will|shall|should} we {eat|have} for lunch?
Peas by the {thousand|hundred|1000} said Dr. Munchauson; {that|is} what he said.

newline
But there are no {misters|doctors} here good sir!
Help us if there is an emergency.

newline
I am the {very last|last} sentence for this {instance|example}.

相关问题 更多 >

    热门问题