字典和输入:如果 `input` 包含我想要打印值的任何键
Dictionary and Input: if the `input` contains any of the keys I want to print the value
我正在尝试构建一种简单的聊天机器人,但是当 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!")
您可以执行以下操作。
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!")
检查给定的文本是否是字典只会在准确的文本在字典中时给出结果,所以如果您检查 "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
我正在尝试构建一种简单的聊天机器人,但是当 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!")
您可以执行以下操作。
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!")
检查给定的文本是否是字典只会在准确的文本在字典中时给出结果,所以如果您检查 "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