[英]python exact substring match
I have a list of dishes and a sentence. 我有一份菜单和一句话。
I want to check if a dish is present in the sentence. 我想检查句子中是否有菜。 However, if I do a normal
但是,如果我做正常的话
if dish in sentence:
I will basically get a substring matching. 我基本上会得到一个子串匹配。 My problem is that say I have a
我的问题是说我有一个
dish='puri'
sentence='the mutton shikampuri was good'
the above code still matches puri with shikampuri which i don't want. 上面的代码仍然匹配puri与shikampuri,我不想要。
If I try tokenizing the sentence, I will not be able to match dishes like dish='puri bhaji' 如果我尝试将句子标记,我将无法匹配像dish ='puri bhaji'这样的菜肴
Is there any way I can ignore the matches which don't begin with my dish string? 有什么方法可以忽略不以我的菜谱开头的比赛吗? Basically, I want to ignore patterns like 'shikampuri' when my dish is 'puri'.
基本上,当我的菜是'puri'时,我想忽略像'shikampuri'这样的模式。
What you need is re.search
with \\b
. 你需要的是
re.search
与\\b
。
import re
if re.search(r"\b"+dish+r"\b",sentence):
You could write: 你可以写:
if dish in sentence.split():
This splits sentence by space into a list and looks for a dish in the list of words. 这将句子按空格分成列表,并在单词列表中查找菜肴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.