如何将文本文件中的单词分配给python中的变量

时间:2015-04-16 11:37:29

标签: python

我有一个文本文件,我需要将这个文本文件中的随机单词(每个单词在一个单独的行上)分配给Python中的变量。然后我需要从文本文件中删除这个单词。

这是我到目前为止所做的。

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)

3 个答案:

答案 0 :(得分:1)

使用random.choice选择一个单词:

variable = random.choice(wordlist)

然后您可以通过另一种理解将其从单词列表中删除:

new_wordlist = [word for word in wordlist if word != variable]

(您也可以filter使用此部分)

然后,您可以使用以下方法将该单词列表保存到文件中:

with open("words.txt", 'w') as f:    # Open file for writing
    f.write('\n'.join(new_wordlist))

如果您只想删除单个单词实例,则应选择要使用的索引。请参阅this回答。

答案 1 :(得分:1)

如果您需要处理重复项,并且每次重新调整列表都是不可接受的,那么有一个简单的解决方案:不是随机选择一个单词,而是随机选择一个索引。像这样:

index = random.randrange(len(wordlist))
word = wordlist.pop(index)
with open("words.txt", 'w') as f:
    f.write('\n'.join(new_wordlist))

或者,或者,使用enumerate同时选择两者:

word, index = random.choice(enumerate(wordlist))
del wordlist[index]
with open("words.txt", 'w') as f:
    f.write('\n'.join(new_wordlist))

答案 2 :(得分:0)

而不是Reut建议的random.choice,我会这样做,因为它保留了重复:

random.shuffle(wordlist) # shuffle the word list 
theword = wordlist.pop() # pop the first element