【问题标题】:Dictionary and Input: if the `input` contains any of the keys I want to print the value字典和输入:如果 `input` 包含我想打印的任何键值
【发布时间】:2021-12-30 18:54:21
【问题描述】:

我正在尝试构建一种简单的聊天机器人,但是当 input 不在字典中时,else 块正在正常工作...

我想打印value,即使input 来自keys 和其他一些词。 例如:

发短信:你好 回答:你好

所以,如果input 包含我想要打印值的任何键。

如果你知道制作这个的方法,请告诉我。谢谢。

words = {"good night": ["nighty night", "good night", "sleep well"],
         "good morning": ["good morning", "wakey-wakey!", "rise and shine!"],
         "hi": ["hello", "hey", "hola"]
         }


text_punk = input("text something: ")

if text_punk in words:
    punk = random.choice(words[text_punk])

    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

【问题讨论】:

  • 在这种情况下,您需要检查字典中的关键字是否存在于输入文本中,例如if any( k in text_punk for k in word):...
  • 感谢@Copperfield 的回答。我试过了,但是当我运行代码时我得到了一个 KeyError。
  • 哦对了,你还需要确定哪个key给了匹配,上面的代码只说有匹配
  • 是的,你有什么解决办法吗?

标签: python dictionary input chatbot


【解决方案1】:

您可以执行以下操作。

import random
words = {"good night": ["nighty night", "good night", "sleep well"],
         "good morning": ["good morning", "wakey-wakey!", "rise and shine!"],
         "hi": ["hello", "hey", "hola"]
         }

text_punk = input("text something: ")

greet_words = words.keys() #check if your key words is in input_text.
word_available = [word for word in greet_words if word in text_punk]

if word_available: # if words are available take the first of key.
    punk = random.choice(words[word_available[0]])

    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

【讨论】:

  • 非常感谢@shivankgtm 的帮助,非常感谢。谢谢你:)
【解决方案2】:

检查给定文本是否是字典仅在确切文本在字典中时才给出结果,因此如果您检查 "hi" in words 它会起作用,因为 "hi" 是字典的键之一,这不会对"hi there" 进行部分检查,因为您需要检查输入文本中是否存在字典中的任何键,例如

text_punk = input("text something: ")
for msj,replies in words.items():#with items we get both the key and its value in one go
    if msj in text_punk:
        punk = random.choice(replies)
        print(punk)
        break #with this we stop the loop at the first match

【讨论】:

  • 感谢@Copperfield 的时间和帮助。我真的很感激,这个也很好用。非常感谢:)
猜你喜欢
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 2021-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多