如何在Python中对文本文件中的单词进行排序

2024-03-29 14:40:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

但如何按顺序打印出来呢?你知道吗


Tags: namein脚本forinputrawlineopen
1条回答
网友
1楼 · 发布于 2024-03-29 14:40:36

如果要对每行中的单词进行排序,可以使用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

相关问题 更多 >