2015-07-21 16 views
0

一個文本文件,我已經寫了,我用它來從文本文件打印出所有單詞的Python腳本:如何才能從詞在Python

file = open(raw_input("Enter a file name: ")) 

for line in file: 
    for words in line.split(): 
     print words 

但如何將它們打印出來,以便?

+1

按什麼順序打印出來? – overactor

回答

3

如果你想在每行排序的話,你可以使用sorted

with open(raw_input("Enter a file name: ")) as f : 

    for line in f: 
     for words in sorted(line.split()): 
     print words 

但是如果你想打印所有詞語的排序順序,你需要應用排序對攻戰:

with open(raw_input("Enter a file name: ")) as f : 
    for t in sorted(i for line in f for i in line.split()): 
      print t