Python 在字符串中搜索多个关键字

Python 在字符串中搜索多个关键字,python,python-3.x,Python,Python 3.x,我正在寻找一种尽可能高效地完成这项任务的方法。 下面是我希望它的工作方式。比如说用户输入 "My screen is broken" 脚本找到屏幕上的两个关键字并将其断开,然后打印一个适当的字符串。作为一个书呆子,我想我也许可以用这样一本字典 {"screen", "broken", "smashed":"use a repair kit"} 然后我会在字典里搜索所有的键。 但经过进一步研究,这似乎是不可能的 那么,最好的方法是什么呢?我想可能是sql,但我想知道是否有更好的方法只涉及pyt

我正在寻找一种尽可能高效地完成这项任务的方法。 下面是我希望它的工作方式。比如说用户输入

"My screen is broken"
脚本找到屏幕上的两个关键字并将其断开,然后打印一个适当的字符串。作为一个书呆子,我想我也许可以用这样一本字典

{"screen", "broken", "smashed":"use a repair kit"}
然后我会在字典里搜索所有的键。 但经过进一步研究,这似乎是不可能的


那么,最好的方法是什么呢?我想可能是sql,但我想知道是否有更好的方法只涉及python。谢谢,字典键需要是不可变的,您可以使用元组,例如

# {("screen", "broken"): "use a repair kit"}

# input is a keyword in Python, so use input_ instead
input_ = input_.split()
if 'screen' in input_ and 'broken' in input_:
    return "use a repair kit"

如果你只是在寻找屏幕和坏的,像这样的东西可以工作

sentence = "My screen is broken"
keys = ["screen", "broken"]

if all(i in sentence for i in keys):
    print "Use a repair kit"

基于Zyzue的答案,您可以让它检查某些值,但不是所有值。这将适用于上面的代码,但如果您想对其他名称进行分组,可以将多个元组嵌套在一起

sentence = "My screen is smashed"

solution_dict = {}
solution_dict[("screen", ("broken", "smashed"))] = "use a repair kit"

#If value is a tuple, run function on every value and return if there are any matches
#If not, check the word is part of the sentence
def check_match(sentence_words, keyword):
    if isinstance(keyword, tuple):
        return any([check_match(sentence_words, i) for i in keyword])
    return keyword in sentence_words

#Make sure each value in the main tuple has a match
sentence_words = [i.lower() for i in sentence.split()]
for k,v in solution_dict.iteritems():
    if all(check_match(sentence_words, i) for i in k):
        print v
因此,您将得到如下结果:

>>> sentence = "My screen is smashed"
use a repair kit
>>> sentence = "My screen is smashed and broken"
use a repair kit
>>> sentence = "My screen is broken"
use a repair kit
>>> sentence = "My phone is broken"
(nothing)

要使用手机,以及iphone和android,您可以这样设置,将iphone和android放在另一个元组中并没有什么区别,只是将其更好地分组。解决方案[screen,phone,android,iphone,Breaked,Splassed]=如果您能为查找算法添加一个片段,那将是非常棒的,因为这似乎是问题的第二点。需要更好的问题定义,所以它只是关于查找“screen”和“Breaked”?据我所知,查找screen,摔碎了@Lil B:请澄清。我只想看看屏幕,我已经更新了答案,但看起来太简单了。
>>> sentence = "My screen is smashed"
use a repair kit
>>> sentence = "My screen is smashed and broken"
use a repair kit
>>> sentence = "My screen is broken"
use a repair kit
>>> sentence = "My phone is broken"
(nothing)