Search code examples
pythonattributeerror

Python. AttributeError: 'str' object has no attribute for the words


GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "whats up",)
GREETING_RESPONSES = ["sup bro", "hey", "*nods*", "hey you get my snap?"]
def check_for_greeting(sentence):
    for word in sentence.words:
        if word.lower() in GREETING_KEYWORDS:
             return random.choice(GREETING_RESPONSES)
user= input(">>> ")
check_for_greeting(user)

AttributeError: 'str' object has no attribute 'words'. sentence.words is not proper. How to get the GREETING_RESPONSES if user is giving input in GREETING_KEYWORDS. I am using python 3.5


Solution

  • The variable sentence is a string. I know that the intention is that it is a sentence with words in it, but as far as Python is concerned it is only a string with characters in it. sentence only contains "words" because you intend that " " is a special character that divides the characters in the string into words. You have to tell Python about that intention. Use the split() method to do that:

    def check_for_greeting(sentence):
        words = sentence.split()
        for word in words:
            if word.lower() in GREETING_KEYWORDS: