Python搜索两个单词正则表达式

时间:2015-01-17 21:50:43

标签: python regex search nltk textblob

我试图找出一个句子是否包含短语“go * to”,例如“go to to”,“go up to”等等。我正在使用Textblob,我知道我可以使用下面:

search_go_to = set(["go", "to"])
go_to_blob = TextBlob(var)
matches = [str(s) for s in go_to_blob.sentences if search_go_to & set(s.words)]
print(matches)

但是这也会返回句子,比如“去那边把它带给他”,这是我不想要的。任何人都知道如何做text.find(“go * to”)?

4 个答案:

答案 0 :(得分:3)

尝试使用:

for match in re.finditer(r"go\s+\w+\s+to", text, re.IGNORECASE):

答案 1 :(得分:2)

使用generator expressions

>>> search_go_to = set(["go", "to"])
>>> m = ' .*? '.join(x for x in search_go_to)
>>> words = set(["go over to", "go up to", "foo bar"])
>>> matches = [s for s in words if re.search(m, s)]
>>> print(matches)
['go over to', 'go up to']

答案 2 :(得分:1)

试试这个

text = "something go over to something"

if re.search("go\s+?\S+?\s+?to",text):
    print "found"
else:
    print "not found"

正则表达式: -

\s is for any space
\S is for any non space including special characters
+? is for no greedy approach (not required in OP's question)

所以re.search("go\s+?\S+?\s+?to",text)会匹配"something go W#$%^^$ to something",当然这也是"something go over to something"

答案 3 :(得分:0)

这有用吗?

import re
search_go_to = re.compile("^go.*to$")
go_to_blob = TextBlob(var)
matches = [str(s) for s in go_to_blob.sentences if search_go_to.match(str(s))]
print(matches)

正则表达式的解释:

^    beginning of line/string
go   literal matching of "go"
.*   zero or more characters of any kind
to   literal matching of "to"
$    end of line/string

如果您不希望“转到”匹配,请在\\b之前和to之后插入go(字边界)。