【发布时间】:2022-01-02 09:58:18
【问题描述】:
我正在开发一种聊天机器人。我想知道是否有办法在字典中使用input 作为value。例如:当输入是“我的名字是 x”时,我想得到答案“Hello x”。
我试过这个:"my name is (.*)": ["Hello ! % 1"],但效果不佳。我想,我需要定义 (.*) 和 %1 但我不知道怎么做。
如果你知道一种方法,请帮助我。谢谢。
words = {"good night": ["nighty night", "good night", "sleep well"],
"good morning": ["good morning", "wakey-wakey!", "rise and shine!"],
"hi": ["hello", "hey", "hi"],
"how are you": ["I am good, thank you", "Pretty good,thank you", "Very well, thanks",
"I am doing great thanks", "Better than some, not as good as others",
"I am better now, it is good to talk to you"],
"bye": ["see you later", "bye", "bye-bye", "see you soon", "bye for now", "catch you later"],
"my name is (.*)": ["Hello ! % 1"]
}
text_punk = input("text something: ")
greet_words = words.keys() #check if the 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!")
【问题讨论】:
-
输入
good时,你不能得到晚安或早安的答案,这正常吗? -
尝试使用正则表达式来匹配这样的键:stackoverflow.com/a/21025121/17706960
-
@azro 好吧,我认为是?您应该输入整个键来获取值,不是吗?
标签: python dictionary input chatbot