用于查找文本中所有句子的正则表达式?

8 投票
7 回答
44019 浏览
提问于 2025-04-16 03:10

我一直在尝试自学Python中的正则表达式,想把一段文本中的所有句子打印出来。过去三个小时我一直在调整正则表达式,但都没有成功。

我刚刚尝试了以下代码,但没有任何效果。

p = open('anan.txt')
process = p.read()
regexMatch = re.findall('^[A-Z].+\s+[.!?]$',process,re.I)
print regexMatch
p.close()

我的输入文件是这样的:

OMG is this a question ! Is this a sentence ? My.
name is.

这段代码没有任何输出。但是当我去掉“My. name is.”这部分时,它却把“OMG is this a question”和“Is this a sentence”一起打印出来,感觉它只读取了第一行。

有没有什么好的正则表达式解决方案,可以找到文本文件中的所有句子——无论句子是否换行——并且能够读取整个文本?谢谢。

7 个回答

2

编辑:现在它也可以处理多行句子了。

>>> t = "OMG is this a question ! Is this a sentence ? My\n name is."
>>> re.findall("[A-Z].*?[\.!?]", t, re.MULTILINE | re.DOTALL )
['OMG is this a question !', 'Is this a sentence ?', 'My\n name is.']

还有一件事需要解释 - re.DOTALL. 这个符号可以匹配换行符,具体说明可以在这里找到。

5

你的正则表达式有两个问题:

  1. 你的表达式用到了 ^$,这两个符号分别代表“行的开始”和“行的结束”。这意味着你的模式是在寻找整整一行的内容。
  2. 你在标点符号前面查找 \s+,这个表示的是“一个或多个空白字符”。如果在标点符号前面没有空白字符,那么这个表达式就不会匹配成功。
10

像这样是可以工作的:

## pattern: Upercase, then anything that is not in (.!?), then one of them
>>> pat = re.compile(r'([A-Z][^\.!?]*[\.!?])', re.M)
>>> pat.findall('OMG is this a question ! Is this a sentence ? My. name is.')
['OMG is this a question !', 'Is this a sentence ?', 'My.']

注意到 name is. 没有出现在结果中,因为它的开头不是大写字母。

你的问题出在使用了 ^$ 这两个符号,它们是针对整个文本的。

撰写回答