Francesco Mantovani
Francesco Mantovani

Reputation: 12347

How order words from a text file in Python

I've written a Python script which I use to print out all words from a text file:

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

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

But how to print them out in order?

Upvotes: 0

Views: 148

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

If you want to sort the words in each line you can use sorted:

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

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

But if you want to print all the words in a sorted order you need to apply the sort on all 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

Upvotes: 3

Related Questions