簡體   English   中英

如何在Python中從文本文件中排序單詞

[英]How order words from a text file in Python

我寫了一個Python腳本,用於打印文本文件中的所有單詞:

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

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

但是如何按順序打印出來呢?

如果要對每一行中的單詞進行排序,可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM