简体   繁体   English

在读取行的行时在python中替换换行符

[英]Replace newline in python when reading line for line

I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\\n' ' '. 我正在尝试在python中的文本上做一个简单的解析,使用tr'\\ n'''在bash中没有问题。 Basically to get all of the lines on a single line. 基本上将所有行都放在一条线上。 In python print line is a bit different from what I understand. 在python中,打印行与我了解的有所不同。 re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. re.sub找不到我的新行,因为即使我将其打印到输出时它也并不存在。 Can someone explain how I can work around this issue in python? 有人可以解释如何在python中解决此问题吗?

Here is my code so far: 到目前为止,这是我的代码:

# -*- iso-8859-1 -*-
import re
def proc():
    f= open('out.txt', 'r')
    lines=f.readlines()
    for line in lines:
        line = line.strip()
        if '[' in line:
            line_1 = line
            line_1_split = line_1.split(' ')[0]
            line_2 = re.sub(r'\n',r' ', line_1_split)
            print line_2
proc()

Edit: I know that "print line," will print without the newline. 编辑:我知道“打印行,”将打印没有换行符。 The issue is that I need to handle these lines both before and after doing operations line by line. 问题是我需要在逐行进行操作之前和之后都处理这些行。 My code in shell uses sed, awk and tr to do this. 我在Shell中的代码使用sed,awk和tr来执行此操作。

You can write directly to stdout to avoid the automatic newline of print : 您可以直接写到stdout来避免自动换行print

from sys import stdout
stdout.write("foo")
stdout.write("bar\n")

This will print foobar on a single line. 这将在一行上打印foobar

When you call the print statement, you automatically add a new line. 调用print语句时,将自动添加新行。 Just add a comma: 只需添加一个逗号:

print line_2,

And it will all print on the same line. 它将全部打印在同一行上。

Mind you, if you're trying to get all lines of a file, and print them on a single line, there are more efficient ways to do this: 请注意,如果您尝试获取文件的所有行,并将它们打印在一行上,则可以使用更有效的方法:

with open('out.txt', 'r') as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        # Some extra line formatting stuff goes here
        print line, # Note the comma!

Alternatively, just join the lines on a string: 或者,只需在字符串上连接各行:

everything_on_one_line = ''.join(i.strip() for i in f.readlines())
print everything_on_one_line

Using with ensures you close the file after iteration. 使用with可确保您在迭代后关闭文件。

Iterating saves memory and doesn't load the entire file. 迭代可节省内存,并且不会加载整个文件。

rstrip() removes the newline in the end. rstrip()最终删除换行符。

Combined: 合并:

with open('out.txt', 'r') as f:
    for line in f:
        print line.rstrip(),

Use replace() method. 使用replace()方法。

file = open('out.txt', 'r')
data = file.read()
file.close()
data.replace('\n', '')

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

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