2016-04-17 36 views
-1

我正在編寫一個程序,用於將文本中的文本讀入列表中,並使用分割功能將其分割成單詞列表。對於每個單詞,我需要檢查它是否已經在列表中,如果不是,我需要使用append函數將它添加到列表中。Python將文字附加到文件列表中

所需的輸出是:

['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'] 

我的輸出是:

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

我一直在嘗試開始時對它進行排序和刪除雙方括號 「[[&]」並結束,但我無法這樣做。由於某種原因sort()函數似乎不起作用。

請讓我知道我犯了什麼錯誤。

word_list = [] 
word_list = [open('romeo.txt').read().split()] 
for item in word_list: 
    if item in word_list: 
     continue 
    else: 
     word_list.append(item) 
word_list.sort() 
print word_list 
+0

作爲TerryA說,你需要2名獨立的名單的工作,但你的代碼使用語句輸入列表和輸出列表都是'word_list',並且你正在使用'[open('romeo.txt').read().span()]'在列表內創建一個列表。最有效的方法是使用'set',但我想你正在做一個家庭作業,你必須使用列表來完成。您還應該瞭解如何使用'with'來打開文件。 –

+0

聲明 「開放('remeo.txt).read()。分裂()」 返回一個列表已經所以從「刪除[] ['開放('remeo.txt).read()。分裂()] 「 – pitaside

回答

0

使用兩個單獨的變量。此外,str.split()返回一個列表,所以沒有必要把[]周圍:

word_list = [] 
word_list2 = open('romeo.txt').read().split() 
for item in word_list2: 
    if item in word_list: 
     continue 
    else: 
     word_list.append(item) 
word_list.sort() 
print word_list 

在你檢查if item in word_list:的那一刻,這將永遠是正確的,因爲itemword_list。使item從另一個列表中迭代。

+0

感謝您的幫助!我是Python新手,這非常有幫助。 – Chandra

+0

@Chandra沒問題!一定要接受答案! – TerryA

0

卸下支架

word_list = open('romeo.txt').read().split() 
0

分割返回一個列表,因此沒必要把open...split方括號括起。刪除重複使用一組:

word_list = sorted(set(open('romeo.txt').read().split())) 
print word_list 
0

如果順序並不重要,這是一個一個襯墊

uniq_words = set(open('romeo.txt').read().split()) 

如果訂單事宜,然後

uniq_words = [] 
for word in open('romeo.txt').read().split(): 
    if word not in uniq_words: 
     uniq_words.append(word) 

如果你想排序,然後採取第一種方法,並使用sorted()

0

open('remeo.txt).read().split()已經返回一個列表,以便[]從[open('remeo.txt).read().split() ]

除去如果我說

word = "Hello\nPeter" 
s_word = [word.split()] # print [['Hello', wPeter']] 
But 
s_word = word.split() # print ['Hello', wPeter'] 
相關問題