-3

I am trying to make a program that takes a file which contains a list of words and user must enter a word that exists in the file. Can you tell me where is the wrong?

file = open('filename')
word_list = file.readlines()
print(word_list)
while True:
    word = input('type in word, must be in English and at least 3 letters long: ')
    if word in word_list:
        break;
    else:
        print("Try Again")
D.A.G.D
  • 23
  • 1
  • 11

1 Answers1

0

Try this:

file = open('filename', 'r')
word_list = []
for line in file:
    line = line.strip()
    list = line.split()
    word_list.extend(list)

word_list = list(set(word_list))  # Make list with unique values.
while True:
    word = input('type in word, must be in English and at least 3 letters long: ')
    if word in word_list:
        break
    else:
        print("Try Again")
file.close()
Kamejoin
  • 347
  • 2
  • 8
  • > Can you tell me where is the wrong? – vaultah Dec 04 '15 at 13:43
  • 1
    @vaultah, the problem is that in the posted code, the file.readlines() results in a list of strings that are terminated in '\n'. As @Kevin hinted above, this causes your comparisons to fail because `'a' in ['a\n', 'b\n']` will evaluate to false. – JCVanHamme Dec 04 '15 at 14:00
  • @JCVanHamme: yes. Kamejoin decided to not include the explanation in their answer. – vaultah Dec 04 '15 at 14:06
  • Actually.. When i run it with a small file i can execute it... But when i run it with a large text file (with many many words) i cant execute it... Any thoughts? – D.A.G.D Dec 04 '15 at 14:16