1

My code that searches for a word in a text file works only once before it keeps printing "Word is not found in word list." (I'm making a Python wordle game and I'm trying to check if the guess is in the word list that I have)

import random

count = 0

whichword = random.randint(0, 5756)

f = open("wordlist.txt","r")

file = open("wordlist.txt")

word = f.readlines()[whichword]

while count < 6:
   guess = input("Guess a 5-letter word: ")

  if len(guess) > 5:
    print("There are more than 5 letters.")
  elif len(guess) < 5:
    print("There are less than 5 letters.")
  elif(guess not in file.read()):
    print("Word is not in word list.")

  count += 1

Basically when I input a word that is in the wordlist, it'll not do anything the first time, but the second time I input a word, it'll output "Word is not in word list." every single time even if the word is in the word list. Does anyone know how I can fix this?

Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
Stitchy
  • 11
  • 1
  • Welcome to SO! This question has been voted to be closed on the basis of duplicates. Can you let us know if your question doesn't satisfy the answers supplied on those recommended duplicates? – bonCodigo Aug 03 '22 at 09:41

1 Answers1

0

You'd have to reset the file pointer to the beginning of the file (e.g. using f.seek(0,0) after each .read(). Else it just stays at the end of the file and there is nothing else to read...

There are other issues with your code though. readlines() will keep the line-ending so your word probably looks like aword\n.

also: if you have fewer words than 5756 you could end up with an IndexError.

Finally: You don't have any "action" defined for a correct guess!

All this addressed:

import random

with open("./wordlist.txt") as f:
    words = [line.strip() for line in f]

word = random.choice(words)

count = 0
while count < 6:
    guess = input("Guess a 5-letter word: ")

    if len(guess) > 5:
        print("There are more than 5 letters.")
    elif len(guess) < 5:
        print("There are less than 5 letters.")
    elif guess not in words:
        print("Word is not in word list.")
    else:
        print("Yay!")
        break

    count += 1
Sebastian Loehner
  • 1,302
  • 7
  • 5