5

我想查找一个短语,最多匹配几个单词,但如果我找到另一个特定的短语,请尽早停止。

例如,我想匹配“going to the”之后最多三个单词,但如果遇到“to try”则停止匹配过程。因此,例如“going to the luna park”将导致“luna park”;“going to the capital city of Peru”将产生“capital city of”,“going to the moon to try some cheesecake”将产生“moon”。

可以用一个简单的正则表达式(最好在 Python 中)来完成吗?我已经尝试了所有我能想到的组合,但惨遭失败:)。

4

2 回答 2

5

这个匹配最多 3 个 ( {1,3}) 单词going to the,只要它们后面没有 try ( (?!to try)):

import re
infile = open("input", "r")
for line in infile:
    m = re.match("going to the ((?:\w+\s*(?!to try)){1,3})", line)
    if m:
        print m.group(1).rstrip()

输出

luna park
capital city of
moon
于 2013-03-22T07:46:45.883 回答
-2

我认为您正在寻找一种从句子中提取专有名词的方法。您应该查看 NLTK 以获得正确的方法。正则表达式只能对有限的上下文无关语法有所帮助。另一方面,您似乎要求能够解析非平凡的人类语言(对于计算机)。

于 2013-03-22T07:28:07.590 回答