简体   繁体   中英

Reversing each line in a function, but the output is printing as one line

I am trying to reverse each word in a multi-lined file and print the words on the same line. So basically, if the inputted text was:

I like to run.

Running is fun.

The end.

I would want the output to read:

I ekil ot .nur

gninnuR si .nuf

ehT .dne

but it is being output as

I ekil ot .nur gninnuR si .nuf ehT .dne

My code so far goes like this:

f = open(file, "r")    #the input goes here
data = f.read()
for line in data:
    reverse = ' '.join(line[::-1] for line in data.split())

print(reverse)

How can I fix this to print line by line? Any help appreciated, thanks.

You will need to split on \\n to operate on each line. Your code currently performs splitting on whitespace (by default) which includes both spaces and newlines, that's the reason why you are getting all words on a single line.

Just use the readlines() method which already gives you a list on lines in the file like this:

with open('file', 'r') as f:
     data=f.readlines()
     for line in data:
             print(' '.join(word[::-1] for word in line.split()))

And here is the output:

I ekil ot .nur
gninnuR si .nuf
ehT .dne

You should first split the lines by .split("\\n") then reverse each word in the line and join them back again.

data = f.read()
for line in data.split("\n"):
    print (' '.join([l[::-1] for l in line.split()]))

output:

I ekil ot .nur 
gninnuR si .nuf 
ehT .dne

Join again on the new line after splitting on it. If you don't use a for loop and opt for a single :

s = """I like to run.

Running is fun.

The end."""
rev = "\n".join(' '.join(sb[::-1] for sb in sub.split(' ')) for sub in s.split('\n'))

Now rev looks like your expected output:

I ekil ot .nur

gninnuR si .nuf

ehT .dne

The program has some issues:

# opens the file but never closes it explicitly.
f = open(file, "r")    #the input goes here

# reads the whole file as one long string.
data = f.read()

# iterates one character at a time through the string (about 40 loops)
for line in data:
    # Computes the same thing about 40 times on the entire file in "data".
    reverse = ' '.join(line[::-1] for line in data.split())

# prints only the last computation.
print(reverse)

Here's the fix:

# closes the file when with block exits
with open(file) as data:
    # data is a file iterator.  This reads one *line* at a time.
    for line in data:
        # split on whitespace getting words, reverse word, and join again.
        print(' '.join(word[::-1] for word in line.split()))

Output:

I ekil ot .nur
gninnuR si .nuf
ehT .dne

there are 3 problems with your code.

  1. The read method literally reads a file as in letter by letter which results in letters being printed for every line. In order to solve this you need to read each file by lines. You can do this by using the " readlines " method.

  2. This ties in to the first problem the join method is unnecessary. In fact the only reason you're probably using it is because of the first problem

  3. your reverse variable is local to the for loop as a result printing it outside the for loop is not a good ideas you should print it inside the for loop

here is your code slightly tweaked

import os

f = open(file, "r")
data = f.readlines() # changed "read()" to "readlines()"
for line in data:
    reverse = line.strip()[::-1] # removed "join" method

    print(reverse) # called "print" function within the for loop

here is another way of doing it.

import os


with open('input.txt') as fl:
    for line in fl:
        reverse_line = line.strip()[::-1]
        print(reverse_line)

You can use built-in function reversed() that returns reversed list. And join "\\n" at the end of each line.

reversed_ans = str()

with open('file', 'r') as f:
        data = f.readlines()
        for line in data:
            reversed_ans += " ".join(["".join(reversed(x)) for x in line.split()]) + "\n"


print(reversed_ans)

This solution is useful if you want return reversed_ans in a function. Or if you want insert that string in another file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM