Reputation: 13
I have a .txt filled with 4000 different words that are listed vertically. I'm supposed to find the position of a certain word that I input, but I get really weird values for the position for the word's that do exist in the file. This is what my code looks like so far
So, the very first word on the list is 'the', so if I were to input into the search_word input 'the', I would get a zero when I'm supposed to get 1. Another example, is if I input 'be', I'd get 4 when it's supposed to be ranked at 2.
I think the problem is that my code is only scanning each character in the list instead of scanning each word separately. I have no clue how to fix this!
Upvotes: 1
Views: 760
Reputation: 106533
You can use enumerate
to generate ranking numbers instead, and the for-else
construct to output the word and break
the loop as soon as the word is found, or wait until the loop finishes without breaking to decide that there is no matching word found:
with lexicon_file as file:
for i, w in enumerate(file, 1):
if search_word == w.rstrip():
print("Accoding to our Lexicon, '%s' is ranked number %d in the most common word in contemporary American English" % (search_word, i))
break
else:
print("According to our Lexicon, '%s' is NOT in the 4000 most common words of contemporary American English")
Upvotes: 1