2015-04-16 60 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)) 
相關問題