2017-06-21 38 views
-1

在我的線上代碼我不知道爲什麼它是錯誤的我嘗試了巨大的不同方式,但他們不工作。我希望它打印出來:第6行輸入錯誤?

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

romeo.txt是文本文檔名稱 這是什麼裏面:

「但軟打破它是通過窗戶那邊什麼光東, 朱麗葉是日頭出現美麗的太陽,殺死羨慕月亮誰是 已經面色慘白同悲「

而且輸出是按字母順序。

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

@折速謝謝 –

回答

1
fname = "romeo.txt" 
fh = open(fname) 
lst = [] 
for line in fh: 
    words = lst.split(line) # this comes first 
    lst.extend(words) # add all the words to the current list 

lst = sorted(lst) # sorts lexicographically 
print lst 

評論中的代碼。基本上,分割你的生產線並將其積累在你的清單中。排序應該在最後完成一次。


A(略)更Python的解決方案:

import re 
lst = sorted(re.split('[\s]+', open("romeo.txt").read(), flags=re.M)) 

正則表達式將文本拆分成基於正則表達式(分隔符爲空格)單詞的列表。其他一切基本上都是多行縮寫爲1.