简体   繁体   English

搜索并替换上一行python

[英]Search and replace previous line python

In a file I have the following text: 在文件中,我有以下文本:

 xxxxxx
    PCTFREE    10
    INITRANS   8
    MAXTRANS   255
    STORAGE    (
                BUFFER_POOL      DEFAULT
               ),
)

I am trying to search for line that startswith(")") and remove the "," from the previous line. 我正在尝试搜索开头为(“)”)的行,并从上一行中删除“,”。

with open('filename') as f:
    print(f.read().replace(',\n)','\n)')

What you're asking for in your description doesn't match anything in your sample input, or even come close to it. 您在描述中要求的内容与示例输入中的任何内容都不匹配,甚至接近。 None of your lines starts with ) . 您的所有行都不以)开头。 One of your lines starts with some whitespace and a ), but the line before that is a blank line, and the last non-blank line before that doesn't have a comma anywhere to remove. 您的一行以空白和a开头,但之前的行是空白行,而该行之前的最后一个非空白行没有逗号可删除。

But I'll ignore the sample input and explain how to do what you were asking for in the description. 但是,我将忽略样本输入,并在说明中解释您要如何做。

The simplest way is to just keep track of the previous line while iterating the lines: 最简单的方法是在迭代各行时只跟踪上一行:

lastline = None
for line in infile:
    line = line.rstrip()
    if line.startswith(")"):
        if lastline is not None:
            lastline = lastline.rstrip(",")
    if lastline is not None:
        outfile.write(lastline + '\n')
    lastline = line
if lastline is not None:
    outfile.write(lastline + '\n')

You can make this a little cleaner and more compact by using a pairwise iterator wrapper like the one in the itertools recipes , but slightly modified to include the "extra" pair at the end: 您可以通过使用pairwise迭代器包装器(如itertools配方中的包装器)来使其更简洁,更紧凑,但稍作修改以在末尾包含“额外”对:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue='')

stripped = (line.rstrip() for line in infile)
for line, nextline in pairwise(stripped):
    if nextline.startswith(")"):
        line = line.rstrip(",")
    if line is not None:
        outfile.write(line + '\n')

You can loop over the text line by line and check one index ahead for a ) : 您可以逐行遍历文本,然后检查一个索引前面的)

new_s = [i.strip('\n') for i in open('filename.txt')]
final_data = '\n'.join(new_s[i][:-1] if new_s[i+1].startswith(')') else new_s[i] for i in range(len(new_s)-1))

Output: 输出:

xxxxxx
PCTFREE    10
INITRANS   8
MAXTRANS   255
STORAGE    (
        BUFFER_POOL      DEFAULT
       )
)

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

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