Search code examples
pythonstringany

Searching text to see if a list of words are there, and if there is, return the text around the word?


I have a function that currently searches text to see if any of my keywords are mentioned within it. I want to enhance this function to return the keyword found and 25 words after it is identified. My code is below, but will not work due to "word" not being identified:

def searching(text):
    key_words = ["address","home", "location", "domicile"]
    if any(word in text for word in key_words):
        statement = text[text.find(word) + 1:].split()[0:20]
        my_return = " ".join(statement)
        return my_return 
    else:
        return "No result"

text = I have a pretty good living situation. I am very thankful for my home located in Massachusetts.

I would expect my function to return "home located in Massachusetts" but I am getting an error.

NameError: name 'word' is not defined

Any ideas?


Solution

  • You can split string to the words and check the result list.

    You are returning in function so it just returned just after the first iteration, you can provide keywords in the argument.

    The result you are expecting can be obtained like this:

    def searching(text):
        key_words = ["address","home", "location", "domicile"]
        for word in key_words:
            if word in text.split():
                statement = text[text.find(word) + 0:].split()[0:20]
                my_return = " ".join(statement)
                print(my_return)
            else:
                print("No result")
    
    text = "I have a pretty good living situation. I am very thankful for my home located in Massachusetts."
    
    print(searching(text))
    

    Output

    No result
    home located in Massachusetts.
    No result
    No result
    
    

    For returning the match when it matches the first time, you can do this and remove else.

    def searching(text):
        key_words = ["address","home", "location", "domicile"]
        for word in key_words:
            if word in text.split():
                statement = text[text.find(word) + 0:].split()[0:20]
                my_return = " ".join(statement)
                return my_return
    
    text = "I have a pretty good living situation. I am very thankful for my home located in Massachusetts. You can find me at my address 123 Happy Lane."
    print(searching(text))
    

    Output

    address 123 Happy Lane.