2014-03-03 32 views
1

我是新來的Python ..(我正在學習它一個星期左右) 我想導入一個文件作爲列表,然後我想從中選擇一個隨機單詞來使用它在循環。?我不太確定該怎麼做!在此先感謝如何導入列表? (python)

+0

我印象深刻,你選擇了正確的標籤,給您的明顯不足關於這個問題的知識。你不能'輸入'一個文件,你可以'打開'它!你的文件是什麼樣的? –

+0

你是什麼意思與'從中選擇一個隨機單詞在循環中使用它'? – skamsie

+1

[首先閱讀文檔](http://docs.python.org/2/tutorial/inputoutput.html),一旦遇到特定問題(包括您嘗試的代碼)和它的輸出如何不符合你的期望。嘗試搜索「打開文件蟒蛇」「從列表中的蟒蛇隨機選擇」等 – mhlester

回答

1

下面是一個廣義的形式回答:

f = open("path/to/file", "r") # opens the file as read-only 
content = f.read() # there are easier ways to do this, but.... 
### do whatever you're doing here.... 
f.close() # MAKE SURE YOU CLOSE FILES when you're done with them 
# if you don't, you're asking for memory leaks. 

您還可以使用上下文管理器,但它讀取的稍硬:

with open("path/to/file","r") as f: 
    content = f.read() # again, this is not the BEST way.... 
    ### do stuff with your file 
# it closes automatically, no need to call f.close() 

文件操作之外,這裏的字符串 - >列表的東西:

"a,b,c,d,e,f,g".split(',') 
-> ['a','b','c','d','e','f','g'] 
# str.split creates a list from a string, splitting elements on 
# whatever character you pass it. 

而這裏的random.choice

import random 

random.choice(['a','b','c','d','e','f','g']) 
-> 'c' # chosen by fair dice roll, guaranteed to be random! ;) 
# random.choice returns a random element from the list you pass it 
1

我要去給你,包括一些最佳實踐的例子:

my_list = [] 

打開與上下文管理器的文件,with(它會自動,如果你有一個關閉文件錯誤,而不是您在此處顯示的其他方式),並且使用通用讀取線rU啓用標誌(r是默認設置)。

with open('/path/file', 'rU') as file: 
    for line in file: 
     my_list.extend(line.split()) # this can represent processing the file line by line 

str.split()方法將在空白處分割,留下標點符號。如果您確實需要文字,請使用自然語言工具包,這有助於您更好地保存意義。

您可以用

my_list = file.read().split() 

讀取整個文件全部一次,可連續工作的文件較小,但請記住困難,更大的文件,如果你做到這一點。

使用隨機模塊來選擇你的話(保持你的進口,以你的腳本的頂部,在大多數情況下,雖然):

import random 

my_random_word = random.choice(my_list)