我正在嘗試構建一種簡單的聊天機器人,但是當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!")
uj5u.com熱心網友回復:
您可以執行以下操作。
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!")
uj5u.com熱心網友回復:
檢查給定文本是否是字典僅在字典中存在確切文本時才給出結果,因此如果您檢查"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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/400140.html
下一篇:遍歷嵌套的pythondict
