有没有办法使用 re.findall
或其他正则表达式方法来计算指定顺序中单词出现的次数,并以任意数量的单词分隔?
这是一个“暴力”实现:
def search_query(query, page):
count=i=0
for word in page.split():
if word == query[i]: i+=1
if i==len(query):
count+=1
break
print count
search_query(['hello','kilojoules'],'hello my good friend kilojoules')
1
例如,当查询为 hello kilojoules
时,我想将 hello my goodfriend kilojoules
识别为我的查询实例,但对于 kilojoules是我的好 friend
不算在内。
这是我对令人满意的正则表达式的天真尝试:re.findall('hello\s\Skilojoules','hello myfriend kilojoules')
。这是行不通的。我认为它会起作用,因为我对这句话的理解是“找到由空格或空格分隔的 hello
和 kilojoules
的所有实例”。
最佳答案
我在 re.findall('hello.*?kilojoules','a happy hello my amigo kilojoules now goodbye')
中找到了成功,遵循 stribishev 的建议
关于Python正则表达式查找与其他单词分隔的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372784/