在 python 中搜索关键字

Searching for keywords in python

如果我在 python 中提问,答案是 "There's water in my phone" 之类的句子,我怎样才能让程序检测到单词 "water" 或 "phone"并打印一个解决方案,例如 "Dry your phone"?.

similar_words = ["water","damaged","wet","soaked","battery"]

words = input("Enter a word or sentence: ").strip().split()

for word in words:

if word.lower() in similar_words:

           print ("Go to a mechanic")


else:    

     print ("sorry your answer doesn't match the criteria, please try again")

这是我到目前为止所做的,但是当我用一句话回答问题时,我得到了我想要的解决方案,即 "Go to the mechanic",我是新手所以请原谅我的愚蠢。

一个简单的基本解决方案:

words = input("Enter a word or sentence: ").strip()
words = words.lower()
if 'water' in words and 'phone' in words:
    print('Dry your phone')

这与您的 'problem description' 完全匹配,但如果您输入以下内容,当然也会生成相同的消息:

  • 我的phone
  • 没有水了
  • 我的 phone
  • 里没有水
  • 我的洗澡水里有phone

它会完全忽略:

  • 我想我 phone 弄湿了。

请记住 - 此解决方案无法很好地扩展(当您尝试 'understand' 更多句子时,代码会很快变得复杂),它不理解常见的变体或否定,或同义词。

这实际上不是任何形式的 AI - 您可以轻松地查找特定数字而不是单词。

让计算机真正 'understand' 你的意思 - 所以它知道 'to get wet' 与 'get water on' 相似,并且需要相同的答案,或者识别出“没有”例如,把水放在底片上-完全是另一回事