2013-10-27 17 views
2

我嘗試寫做以下排序開放和寫入文件

  • 打開文件word_list.txt
  • 閱讀本文件的內容到一個列表
  • 排序功能名單按字母順序排列
  • 寫列表中的內容到一個名爲alphabetic.txt

這是我的代碼文件

def alphabetic(): 
    file = open("word-text.txt","r") 
    data=file.read() 
    print (data) 
    file.close() 
    listsort=data 
    listsort.sort() 
    print(listsort) 

每當我嘗試運行這段代碼,我用「文件」將不被排序的名單,我得到下面的結果(這是相同的列表順序,我有),我想以字母順序有錯誤

>>> alphabetic() 
apples 
oranges 
watermelon 
kiwi 
zucchini 
carrot 
okra 
jalapeno 
pepper 
cucumber 
banana 
Traceback (most recent call last): 
    File "<pyshell#32>", line 1, in <module> 
    alphabetic() 
    File "/Users/user/Desk`enter code here`top/Outlook(1)/lab6.py", line 15, in alphabetic 
    listsort.sort() 
AttributeError: 'str' object has no attribute 'sort'` 

我真的很新的程序員對它們進行排序,而我試圖盡我所能,但請清楚,因爲我不是最好的

+0

歡迎堆棧溢出。請儘快閱讀[關於]頁面。我已經刪除了一些可能無關緊要的標籤。你應該用一個語言標籤更新標籤 - 這可能是Python。 –

回答

2

你的方法WASN」因爲read方法只返回一個字符串,所以不起作用。由於Python字符串沒有sort()方法,因此您遇到了錯誤。方法sort適用於lists,如我的方法所示,使用readlines方法。

如果這是你的文件的內容:

apples 
oranges 
watermelon 
kiwi 
zucchini 
carrot 
okra 
jalapeno 
pepper 
cucumber 
banana 

下面是相關的代碼:

with open('word-text.txt', 'r') as f: 
    words = f.readlines() 

    #Strip the words of the newline characters (you may or may not want to do this): 
    words = [word.strip() for word in words] 

    #sort the list: 
    words.sort() 
    print words 

此輸出:

['apples', 'banana', 'carrot', 'cucumber', 'jalapeno', 'kiwi', 'okra', 'oranges', 'pepper', 'watermelon', 'zucchini'] 
+0

謝謝SIR!你拯救了我的生命 – CaVeMaN

+0

@ user2924427:如果我的回答對你有用,那麼請考慮接受。 :) – jrd1