Kass D Kass D - 7 months ago 20
Python Question

Python: If Raw_Input Contains...BLAH

(I am new to Python and programming) I am using

raw_input()
so I can make a program that talks to the user. For example:

Program: How are you?
User: I am doing great!/I feel terrible.

I need my program to respond accordingly, as in "YAY!" or "Aw man... I hope you feel better soon." so can you please give me ways to scan for words such as "good" or "bad" in the user's raw input so my program knows how to respond?

I know a few ways to do this, but the problem is, I want multiple words for it to look for, like great, amazing, and awesome can all be classified into the "good" group. AND, I need it where it doesn't have to be exact. I keep on running into problems where the user has to exactly type, "I am good." instead of all the different variations that they could possibly say it. THANK YOU IN ADVANCE!

Answer

I will try to make it as easy as possible for you to read the comment.

# define response and keywords list
response_and_keywords = {"Cheer up":["sad","bad"],
                         "Cool!":["good","amazing"]} 

# get user input
user_input = raw_input("How are you ?")
# loop through the dictionary
for response,keywords in keywords_and_responses.iteritems():
    # user_input is in keywords list
    if user_input in keywords:
         # say the response!
         print response