当前位置: 首页 > 面试题库 >

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

和丰羽
2023-03-14
问题内容

我一直在尝试用python自学正则表达式,因此我决定打印出文本的所有句子。在过去的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,这是一个问题,这是否是一个句子,就好像它只读第一行一样。

正规表达式的最佳解决方案是什么,它可以找到文本文件中的所有句子(无论句子是否换行,也可以读取整个文本)?谢谢。


问题答案:

像这样的作品:

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

您的问题来自^$锚的使用,它们在整个文本上都有效。



 类似资料: