I am trying to make a program that reads words from a txt file and use them to create a word quiz where you choose the synonym of a given word from 5 options - the correct answer and 4 other random words.
The text file looks something like this:
alleviate,release,slacken
clique,sect,faction,clan
denigrate,minimize,belittle,derogate
...
Here is the code:
import random
b = input('Press enter to start, enter !END to end.')
with open('vocab.txt', 'r') as file:
v = file.readlines()
while b != '!END':
group = random.choice(v)
v.remove(group)
group = group.split(',')
word = random.choice(group)
group.remove(word)
correct = random.choice(group).replace('\n', '')
choices = [correct]
for i in range(4):
group2 = random.choice(v)
v.remove(group2)
group2 = group2.split(',')
ans = random.choice(group2).replace('\n', '')
choices.append(ans)
random.shuffle(choices)
print(word.strip() + ':\n', choices)
b = input('Which is the synonym?(1~5)')
if b == '!END':
continue
a = int(b)
while a-1 != choices.index(correct):
b = input('incorrect, try again!')
if b == '!END':
continue
a = int(b)
print('correct!')
output:
Press enter to start, enter !END to end.
trifling:
['altercation', 'ravenous', 'neophyte', 'clique', 'paltry']
Which is the synonym?(1~5)5
correct!
escape:
['evade', 'churlish', 'expert', 'satisfied', 'worried']
Which is the synonym?(1~5)1
correct!
progeny:
['admit', 'alleviate', 'descendant', 'denigrate', 'dull']
Which is the synonym?(1~5)3
correct!
secondary:
['parallel', 'introduce', 'obeying', 'sympathize', 'regulate']
Which is the synonym?(1~5)1
correct!
poverty:
['impoverishment', 'impel', 'examine', 'pugilist', 'pilfer']
Which is the synonym?(1~5)1
correct!
But for some reason the process only repeats five times before it throws the error:
Traceback (most recent call last):
File "FILE_LOCATION", line 19, in <module>
group2 = random.choice(v)
File "FILE_LOCATION", line 378, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range
I think this might be because the list of words was becoming shorter and shorter, I didn't want any repetition so I removed a word from the list if it has been used before. But the number of remaining words were enough to chose 5 words randomly from after looping the process 5 times. Is there a way to solve this? Any help is greatly appreciated! :)
Aucun commentaire:
Enregistrer un commentaire