2013-04-12 34 views
0

所以我試圖製作一個讀取文件的程序,並將每個單詞存儲到一個字符串列表中。我可以將每行添加到字符串列表中(請參閱下面的代碼),但是如何將每個單詞添加到字符串列表中?將文本文件中的每個單詞存儲到列表中

此外,由於這是一個填字節目,我還會有一些短語,將是什麼樣子,名詞,或身體部位。我如何將身體部分作爲一個字符串存儲到列表中,因爲它在技術上是兩個單獨的單詞?

代碼以供參考:

def main(): 
    file_list = [] 
    while True: #while loop that runs until the user puts in a file name... 
    #or types in quit 
    #asks the user for a file name, or gives them an option to quit 
    file_name = raw_input("Enter in the name of the file, or type in quit to quit: ") 
    if file_name == "quit": 
      sys.exit(0) #quits the program 
    else: 
      try: #attempts to open the file 
       fin = open(file_name) 
       break 
      except: #prints out if file name doesn't exist 
        print "No, no, file no here." 
    for eachLine in fin: #strips out the new lines from the file 
     file_list.append(eachLine.strip()) 
    print file_list 
if __name__ == '__main__': 
    main() 
+0

什麼是你的代碼問題那麼遠? – jamylak

+0

它將文本文件中的每一行添加到列表中,但我需要它添加每個單詞。 – user1768884

回答

2
file_list.extend(eachLine.split()) 
+0

這裏的條是多餘的,'.split()'已經剝離了。 –

+0

這似乎將單詞拆分爲單獨的字母。 我可能會把它寫錯,但我需要一個字符串行的列表,並將它們分成單獨的單詞。 – user1768884

+0

@ user1768884你試過了嗎? – jamylak

相關問題