Mr Whozz
Mr Whozz

Reputation: 41

How to read a text file and output the words in the reversed order? Python

So I'm working on a code that reads a text and outputs on the screen the words in a reversed order meaning if the original text was

hello world
how are you

to:

you are how
world hello

I get it to partially work, the problem is that it outputs it in a single column, but I want it to be in lines.

the code is

for a in reversed(list(open("text.txt"))):
    for i in a:
        a = i.split()
        b =  a[::-1]
        final_string = ''
        for i in b:
            final_string += i + ' '
        print(final_string)

Upvotes: 3

Views: 1908

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123640

You have one loop too many:

for a in reversed(list(open("text.txt"))):
    for i in a:

The first loop produces the lines in the file in reverse order, so a is bound to each line. The second for then loops over each individual character in that line. You then proceed to 'reverse' that character (or an empty list when that character is a space or newline).

You are already using reversed for the file, you can use it for the lines too; combine it with str.join():

for line in reversed(list(open("text.txt"))):
    words = line.split()
    reversed_words = ' '.join(reversed(words))
    print(reversed_words)

Or more concisely still:

print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n')

Demo:

>>> with open('text.txt', 'w') as fo:
...     fo.write('''\
... hello world
... how are you
... ''')
... 
24
>>> for line in reversed(list(open("text.txt"))):
...     words = line.split()
...     reversed_words = ' '.join(reversed(words))
...     print(reversed_words)
... 
you are how
world hello
>>> print(*(' '.join(l.split()[::-1]) for l in reversed(list(open('text.txt')))), sep='\n')
you are how
world hello

Upvotes: 7

Related Questions