我有一些文字是句子,其中一些是问题。我正在尝试创建一个正则表达式,它只会提取包含特定短语的问题,即'NSF':
import re
s = "This is a string. Is this a question? This isn't a question about NSF. Is this one about NSF? This one is a question about NSF but is it longer?"
理想情况下,re.findall会返回:
['Is this one about NSF?','This one is a question about NSF but is it longer?']
但我目前最好的尝试是:
re.findall('([\.\?].*?NSF.*\?)+?',s)
[". Is this a question? This isn't a question about NSF. Is this one about NSF? This one is a question about NSF but is it longer?"]
我知道我需要做一些非贪婪的事情,但我不确定我搞砸了。
答案 0 :(得分:1)
免责声明:答案并非针对通用疑问句分割解决方案,而是展示OP提供的字符串如何与正则表达式匹配。最好的解决方案是使用nltk
和解析句子将文本标记为句子(参见this thread)。
你可能想要用于你发布的字符串的正则表达式是基于匹配所有非最终标点符号的字符,然后匹配你想要出现在句子中的子字符串,然后匹配除最终标点之外的字符串再次。要否定单个字符,请使用否定字符类。
\s*([^!.?]*?NSF[^!.?]*?[?])
请参阅regex demo。
<强>详情:
\s*
- 0+ whitespaces ([^!.?]*?NSF[^.?]*?[?])
- 第1组捕获
[^!.?]*?
- 除.
,!
和?
以外的0个字符,尽可能少NSF
- 您需要出现的值,一系列字符NSF
[^.?]*?
- 同上。[?]
- 文字?
(可以替换为\?
)