如何从Python中的文本文件中订购单词

时间:2015-07-21 08:32:06

标签: python dictionary

我编写了一个Python脚本,用于打印文本文件中的所有单词:

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

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

但是如何按顺序打印出来?

1 个答案:

答案 0 :(得分: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