gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:39 24 4
gpt4 key购买 nike

我一直在尝试自学 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.

这不打印任何输出。但是当我删除“My.name is.”时,它会打印 OMG is this a question 和 Is this a sentence together 就好像它只读第一行一样。

正则表达式的最佳解决方案是什么,它可以找到文本文件中的所有句子——不管句子是否换行——并且还可以读取整个文本?谢谢。

最佳答案

类似这样的东西:

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

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

关于python - 正则表达式查找文本的所有句子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3549075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com