【发布时间】:2016-10-17 17:00:47
【问题描述】:
我有一些文本是句子,其中一些是问题。我正在尝试创建一个正则表达式,它将仅提取包含特定短语的问题,即“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?"]
我知道我需要做一些不贪婪的事情,但我不确定我在哪里搞砸了。
【问题讨论】:
-
试试
r'\s*([^.?]*?NSF[^.?]*?[?])' -
@WiktorStribiżew 谢谢!您能解释一下您所做的一些更改以帮助我自己理解吗?
-
我在哄孩子睡觉。那么,它对你有用吗?关键是我使用否定字符类来匹配特定字符以外的文本块。
-
我认为最好的解决方案是使用
nltk将文本标记为句子并解析句子(参见this thread)。正则表达式在很多情况下都不起作用,请考虑缩写。 -
是的,您的解决方案确实有效。我知道一些 nltk 解析将是最好的方法,但我真的只是在寻找快速破解。基本上我想要一种快速的方法来检查我的语料库中的一些问题语法。有几种变体(ANSF、国家科学基金会等),但我只是想快速浏览一下。
标签: python regex non-greedy