Reputation: 99
I'm making simple keyword recognition program where I have a txt
file and every word is in new line. I open as a list and then I check for every keyword in sentence I will later open from database.
So far I get this error:
TypeError: 'in <string>' requires string as left operand, not list
I get it both needs to be string-string or list-list. I experimented and tried to convert the sentence into list - program returned nothing.
Any suggestions how to make this work, or suggestions how to change things to make it correct?
results = []
with open('words.txt') as inputfile:
for line in inputfile:
results.append(line.strip())
#print results
all_text = 'vistumšākā zaudēt zilumi nāve'
#all_texts = all_text.split()
for word in results:
if results in all_texts:
x += 1
print x
Upvotes: 0
Views: 114
Reputation: 6072
You've got a simple typo here. You're trying to check each word
from your words.txt
file, but you're using results
in your if
statement. Hence the error; Python's saying "I expected this variable to contain a string, but it was actually a list." Change your second for
loop:
for word in results:
if word in all_texts:
x += 1
I've renamed your variables to be more descriptive in the full program below:
word_list = []
with open('words.txt') as inputfile:
for line in inputfile:
word_list.append(line.strip())
source_text = 'vistumšākā zaudēt zilumi nāve'
source_words = source_text.split()
count = 0
for word in word_list:
if word in source_words:
count += 1
print count
Upvotes: 4