我一直在尝试用python自学Regexes,我决定打印出文本的所有句子.我一直在修补过去3个小时的正则表达无济于事.
我只是尝试了以下但无法做任何事情.
p = open('anan.txt')
process = p.read()
regexMatch = re.findall('^[A-Z].+\s+[.!?]$',process,re.I)
print regexMatch
p.close()
Run Code Online (Sandbox Code Playgroud)
我的输入文件是这样的:
OMG is this a question ! Is this a sentence ? My.
name is.
Run Code Online (Sandbox Code Playgroud)
这不打印任何输出.但是当我删除"我的.名字是."时,它打印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.']
Run Code Online (Sandbox Code Playgroud)
注意name is.结果中没有,因为它不是以大写字母开头的.
你的问题来自^$锚的使用,它们适用于整个文本.