I have a text file and I need to assign a random word from this text file (each word is on a separate line) to a variable in Python. Then I need to remove this word from the text file.
This is what I have so far.
with open("words.txt") as f: #Open the text file
wordlist = [x.rstrip() for x in f]
variable = random.sample(wordlist,1) #Assigning the random word
print(variable)
Use random.choice
to pick a single word:
variable = random.choice(wordlist)
You can then remove it from the word list by another comprehension:
new_wordlist = [word for word in wordlist if word != variable]
(You can also use filter
for this part)
You can then save that word list to a file by using:
with open("words.txt", 'w') as f: # Open file for writing
f.write('\n'.join(new_wordlist))
If you want to remove just a single instance of the word you should choose an index to use. See this answer.
If you need to handle duplicates, and it's not acceptable to reshuffle the list every time, there's a simple solution: Instead of just randomly picking a word, randomly pick an index. Like this:
index = random.randrange(len(wordlist))
word = wordlist.pop(index)
with open("words.txt", 'w') as f:
f.write('\n'.join(new_wordlist))
Or, alternatively, use enumerate
to pick both at once:
word, index = random.choice(enumerate(wordlist))
del wordlist[index]
with open("words.txt", 'w') as f:
f.write('\n'.join(new_wordlist))
Rather than random.choice
as Reut suggested, I would do this because it keeps duplicates:
random.shuffle(wordlist) # shuffle the word list
theword = wordlist.pop() # pop the first element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.