2017-02-14 85 views
2

本週的分配是一個關於列表的問題,我無法擺脫列表符號。分割,rstrip,追加列表的使用

打開文件romeo.txt並逐行閱讀。對於每一行,使用split()方法將行分割成單詞列表。該程序應該建立一個單詞列表。對於每行上的每個單詞,檢查單詞是否已經在列表中,並且是否將其附加到列表中。程序完成後,按字母順序對結果詞進行排序和打印。

http://www.pythonlearn.com/code/romeo.txt

fname = raw_input("Enter file name: ") 
fh = open(fname) 
lst = list() 
for line in fh: 
    line = line.split() 
    lst.append(line) 
    lst.sort() 
print lst 
+0

通過使用加入擺脫[] ''。加入(LST)。此外,如果你想檢查重複,你最好使用一套,而不是使用列表。 –

回答

0

正如在評論中提到一個set會爲了這個美好的,但由於分配約爲名單,可以是這樣的:

list_of_words = [] 
with open('romeo.txt') as f: 
    for line in f: 
     words = line.split() 
     for word in words: 
      if word not in list_of_words: 
       list_of_words.append(word) 

sorted_list_of_words = sorted(list_of_words) 
print(' '.join(sorted_list_of_words)) 

輸出:

Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder 

從用戶請求的文件名的替代解決方案,採用繼續並且是與Python 2.x的兼容:

fname = raw_input('Enter file: ') 

wordlist = list() 
for line in open(fname, 'r'): 
    words = line.split() 
    for word in words: 
     if word in wordlist: continue 
     wordlist.append(word) 

wordlist.sort() 
print ' '.join(wordlist) 

輸出:

Enter file: romeo.txt 
Arise But It Juliet Who already and breaks east envious fair grief is kill light moon pale sick soft sun the through what window with yonder