我正在寻找一种尽可能高效完成此任务的方法。 以下是我希望它如何工作。用户输入
"My screen is broken"
该脚本找到两个关键字" screen"和#34;破碎"然后打印一个合适的字符串。作为一个菜鸟我以为我可以使用像这样的字典
{"screen", "broken", "smashed":"use a repair kit"}
然后我会搜索字典中的所有键。 但经过进一步的研究,这似乎是不可能的。
那么最好的方法是什么呢?我想也许是sql,但我想知道是否有更好的方法只涉及python.Thanks
答案 0 :(得分:1)
字典键需要是不可变的,你可以使用元组,例如
# {("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"
答案 1 :(得分:1)
str_replace()
答案 2 :(得分:1)
如果你只是在寻找“屏幕”和“破碎”,这样的事情就可以了。
sentence = "My screen is broken"
keys = ["screen", "broken"]
if all(i in sentence for i in keys):
print "Use a repair kit"
答案 3 :(得分:1)
根据zyxue的回答,您可以检查某些值,但不是全部。这将适用于您的上述代码,但如果您想将其他名称分组,则可以将多个元组嵌套在一起。
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在另一个元组没有区别,但只是将它组合得更好。
solution_dict[(("screen", "phone", ("android", "iphone")), ("broken", "smashed"))] = "use a repair kit"
< / p>