ThanaDaray
ThanaDaray

Reputation: 1693

How to sort words in text file?

In "test_wordss.txt"

A
sentence
is
a
grammatical
unit
consisting
of
one
or
more
words
A

My code:

for line2 in open('C://Users/Desktop/test_wordss.txt'):
    fields2 = line2.rstrip('\n').split('\t')
    print fields2.sort()

The results from my codes come out as None...

Did I do something wrong? Any suggestion for sorting words in text file?

Upvotes: 3

Views: 4245

Answers (5)

ahmadjanan
ahmadjanan

Reputation: 445

for x in word_list:
    ordered = True
    last = ord(x[0])
    
    for char in x[1:]:
        if ord(char) < last:
            flag = False
            break
        last = ord(char)
    
    if ordered:
        print(word)

Upvotes: 0

NPE
NPE

Reputation: 500367

Try:

words = sorted(open('C://Users/Desktop/test_wordss.txt').read().split())
print(words)

There are several problems with your code:

  1. sort() doesn't return the sorted list. It sorts the list in place, and returns None.
  2. Your code attempts to sort the words in each line, and there's only one word per line. It doesn't attempt to work on the entire file at once.

Upvotes: 5

tacaswell
tacaswell

Reputation: 87376

sort sorts the list in-place (doc) and returns None to make that point (so you don't forget about the side-effect you only get the side-effect). Either use

print sorted(fields2)

or

fields2.sort()
print fields2

Upvotes: 1

Matias Rasmussen
Matias Rasmussen

Reputation: 831

Try this:

for line in sorted(file('C://Users/Desktop/test_wordss.txt').read().split("\n")):
    print line

Upvotes: 0

satoru
satoru

Reputation: 33225

sort doesn't return a sorted list, it sort the list in place.

Upvotes: 0

Related Questions