How can I read a text file and output words in reverse order? python

So, I am working on a code that reads text and displays the words in reverse order if the original text is

hello world
how are you

      

in

you are how
world hello

      

I get it to partially work, the problem is it outputs it in one column, but I want it to be in rows.

code

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)

      

+3


source to share


1 answer


You have too many loops:

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

      

The first loop creates lines in the file in reverse order, so it is a

attached to each line. The second for

then iterates over every single character on that line. Then you go to the "reverse" character (or empty list when that character is a space or a new line).

You already use reversed

for a file, you can also use it for strings; 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 succinctly:

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

      

+7


source







All Articles