2015-04-16 62 views
0

我有一个文本文件,我需要从该文本文件(每个单词在单独一行中)为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) 
+0

请问你有什么工作?如果没有,什么不起作用? –

+0

我设法从文本文件分配一个随机单词到一个变量,但我现在正在努力如何从文本文件中删除该随机单词 – sharmacka

回答

1

使用random.choice挑一个字:

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

(您也可以使用filter此:

variable = random.choice(wordlist) 

然后,您可以通过另一种理解从字列表中删除部分)

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

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

如果你想删除单词的单个实例,你应该选择一个索引来使用。请参阅this的答案。

+0

我怀疑他还需要'new_wordlist'写回'单词。尽管我在这里达到了我的思维能力的极限。 :) – abarnert

+0

我已经添加了他可能需要的信息,但初始答案确实回答了标题中的问题。 –

+0

为什么不'word_list.remove(变量)'? – Vincent

0

不是random.choice为Reut的建议,我会做这个,因为它使重复:

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

你怎么知道每次重新洗牌都可以接受? – abarnert

+0

@abarnert你的意思是可接受的?列表总是可以被洗牌。 –

+0

当然,一个列表总是可以被洗牌,但这是一个不同的列表。例如,如果原始列表按照特定的有意义顺序,并且希望能够在文本编辑器中打开它并浏览它,那么现在你不能,而这可能是不可接受的。 – abarnert

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)) 
相关问题