Python Forum

Full Version: Compare all words in input() to all words in file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

So I have revised my code and hope you guys can help me out. My intention is to compare each words from user input to words in a file and print only words not exist from user input. My code is as shown below. I apologized for not know how to insert code correctly.

sentence = input("Enter a sentence: ")

text = sentence.split()

for counter in text:
#    print (str.lower(counter))

    with open('data.txt') as file: 
        content = file.read()

    for counter in content:

        if text in content:
            continue
        if text not in content:
            print(counter)

print('These words not in list')
data.txt
Output:
apples oranges bananas kiwis
Output:
Error:
Enter a sentence: i love apples Traceback (most recent call last): File "test.py", line 13, in <module> if text in content: TypeError: 'in <string>' requires string as left operand, not list
I am not sure how to handle the error.

I only need to pull the words not exist from user input. What I want the output to print is:

Output:
i love These words not in list
Please advise.
First, file.read() returns a string. When you loop through a string (as in for counter in content:), you loop through the characters of the string. You want to loop through the words in content, not the characters. So you need to use the split method as you did for sentence.

Second, as the error you got shows, you want to test for string in list, not list in string. So flip the variables around the in operator.

Third, you first if clause is not needed. If the second if clause doesn't trigger, the loop goes to the next iteration, which is all your first if clause is doing.