Gu-- Gu-- - 3 months ago 13
Python Question

Check if user input contains a word from an array - Python 3

I am writing a code that asks a set amount of questions.
I am trying to have the user input an answer and the code checks the users input for any word in a list of several words.

keywordlist = ("pain", "suffering", "hurt")
question1 = input("how are you feeling?")
if question1.lower() in keywordlist:
print("something here")


I ended up browsing stackoverflow for the answer and came across a post about splitting a string, but I didn't understand it. It was this question.

using this link I switched my code to :

if any(word in Question1 for word in keywordlist.split(",")):


but I got the error:

AttributeError: 'tuple' object has no attribute 'split'


I am new to Python and need the dumbed down version of the accurate way to do this.

Answer

Assuming that you want the user to input a sentence and want to check if any word is in the keyword list:

keywordlist = ("pain", "suffering", "hurt")
question1 = input("how are you feeling?")
input_words=question1.lower().split()
for word in input_words:
    if word in keywordlist:
        print("something here")

The reason if any(word in Question1 for word in keywordlist.split(",")): gave you that error is because you called the split() method on keywordlist which is a tuple. So the error is telling you exactly what you did wrong. You want to split the input into words, the keywordlist already contains words split up into a tuple.

Comments