1

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 enter image description here

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!

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied and offer poor usability. Instead, paste the code as text directly into your question. If you select it and click the `{}` button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code. – ChrisGPT was on strike Oct 26 '18 at 02:39
  • `contents = list(file)` should solve your problem – Joran Beasley Oct 26 '18 at 02:41
  • Possible duplicate of [How to search for a string in text files?](https://stackoverflow.com/questions/4940032/how-to-search-for-a-string-in-text-files) – Edgar Ramírez Mondragón Oct 26 '18 at 04:01

1 Answers1

1

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")
blhsing
  • 91,368
  • 6
  • 71
  • 106