digitalfire
digitalfire

Reputation: 37

Checking keywords from sentence input and then checking text file in Python

I've been learning Python and I've ran into some difficulty. I want to make a program where the user can input a sentence. The program then splits the sentence up and checks the words against a list. If any word is found in the list, it then finds that word in a text file and prints the line of the text file for which the word is located.

So far I have this:

    def getTakeaway():
    list = ["pizza", "italian", "chinese", "indian"]
    query = input("Please say what take away you'd like").lower()
    if set(list).intersection(query.split()):
        with open('takeaway.txt') as f:
            for line in open('takeaway.txt'):
                if query in line:
                    print (line)
                    break
    else:
        print("sorry not found")
getTakeaway()

It works for single word inputs such as 'pizza', however I get nothing back when searching for an input such as 'I would like pizza'.

Thanks in advance.

Edit: I've changed the code to this based on the advice given:

def getTakeaway():
    list = ["pizza", "italian", "chinese", "indian"]
    query = input("Please say what take away you'd like").lower()
    query_words = set(list).intersection(query.split())
    if query_words:
        with open('takeaway.txt') as f:
            for line in open('takeaway.txt'):
                if query_words in line:
                    print (line)
                    break
    else:
        print("sorry not found")
getTakeaway()

and I get this error: if query_words in line: TypeError: 'in ' requires string as left operand, not set

Upvotes: 1

Views: 998

Answers (2)

jogo3000
jogo3000

Reputation: 21

In the line

if query_words in line:

you are using a set which contains set(['i', 'would', 'like', 'some', 'pizza']). The expression "query in line" would now look for the set from the line. You need to iterate through the values in the set, a lot like you are iterating through the lines in the file:

for word in query_words:
    if word in line:
        ...

Upvotes: 1

poolie
poolie

Reputation: 9517

If your intention is to search the lines for words in the intersection of the input and the hotlist, you need to actually do that

query_words = set(list).intersection(query.split())
if query_words:
     ...

Upvotes: 0

Related Questions