![](/img/trans.png)
[英]How to read a text file and output the words in the reversed order? 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.