Home > Net >  Dictionary and Input: if the `input` contains any of the keys I want to print the value
Dictionary and Input: if the `input` contains any of the keys I want to print the value

Time:12-31

I'm trying to build kind of a simple chatbot, but when the input is something out of the dictionary the else block is working as it should be...

I want to print the value even if the input is something from the keys and some other words. for example:

text something: hi there answer: hello

so, if the input contains any of the keys i want to print the value.

please let me know if you know a way to make this. Thank you.

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!")

CodePudding user response:

you can do the following.

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!")

CodePudding user response:

checking if a given text is a dictionary only give a result if the exact text is in the dictionary, so if you check "hi" in words it work because "hi" is one of the key of the dict, this doesn't work for partials check of "hi there", for that you need to check if any of the key in the dict are present in the input text, so something like

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
  • Related