我正在編寫一個程序,用於將文本中的文本讀入列表中,並使用分割功能將其分割成單詞列表。對於每個單詞,我需要檢查它是否已經在列表中,如果不是,我需要使用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
作爲TerryA說,你需要2名獨立的名單的工作,但你的代碼使用語句輸入列表和輸出列表都是'word_list',並且你正在使用'[open('romeo.txt').read().span()]'在列表內創建一個列表。最有效的方法是使用'set',但我想你正在做一個家庭作業,你必須使用列表來完成。您還應該瞭解如何使用'with'來打開文件。 –
聲明 「開放('remeo.txt).read()。分裂()」 返回一個列表已經所以從「刪除[] ['開放('remeo.txt).read()。分裂()] 「 – pitaside