找到所有文本句子的Regex?

2024-06-16 09:42:57 发布

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

我一直在尝试用python自学regex,我决定打印出文本中的所有句子。在过去的3个小时里,我一直在修改正则表达式,但没有结果。

我只是试了一下,但什么也做不了。

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.

这不会打印输出。但当我移除“我的”。名字是,“,它打印OMG这是一个问题,这是一个句子在一起,好像它只读第一行。

regex的最佳解决方案是什么?它可以在文本文件中找到所有的句子,而不管句子是换行还是换行,还可以读取整个文本?谢谢。


Tags: 文本retxtreadisopenthisprocess
3条回答

已编辑:现在它也可以处理多行语句。

>>> 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使.匹配所描述的换行符here

regex中有两个问题:

  1. 你的表达式是anchoredby ^$,它们分别是“行的开始”和“行的结束”锚。这意味着您的模式希望匹配整行文本。
  2. 您正在标点符号前面搜索\s+,标点符号指定one or morewhitespace character。如果标点符号前没有空格,则表达式将不匹配。

像这样的方法有效:

## 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.不在结果中,因为它不是以大写字母开头的。

您的问题来自于^$锚的使用,它们作用于整个文本。

相关问题 更多 >