简体   繁体   English

反转功能中的每一行,但输出打印为一行

[英]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 我觉得.nur

gninnuR si .nuf gninnuR si .nuf

ehT .dne T

but it is being output as 但它被输出为

I ekil ot .nur gninnuR si .nuf ehT .dne 我会选择.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. 您需要分割\\n才能在每一行上进行操作。 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: 只需使用readlines()方法,该方法已经为您提供了文件中的行列表,如下所示:

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. 您应该首先用.split("\\n")分割行,然后反转行中的每个单词,然后将它们重新结合在一起。

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 : 如果您不使用for循环并选择一个:

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: 现在rev看起来像您的预期输出:

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. 您的代码有3个问题。

  1. The read method literally reads a file as in letter by letter which results in letters being printed for every line. read方法按字面意义逐字读取文件,这导致每行打印一个字母。 In order to solve this you need to read each file by lines. 为了解决这个问题,您需要按行读取每个文件。 You can do this by using the " readlines " method. 您可以使用“ readlines”方法执行此操作。

  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 您的反向变量是for循环的局部变量,因此在for循环外部打印它不是一个好主意,您应该在for循环内部打印它

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. 您可以使用内置函数reversed()返回反向列表。 And join "\\n" at the end of each line. 并在每行末尾加入"\\n"

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. 如果要在函数中return reversed_ans ,则此解决方案很有用。 Or if you want insert that string in another file. 或者,如果您想将该字符串插入另一个文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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