Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
搜索并替换前一行python_Python_Python 3.x_Python 2.7 - Fatal编程技术网

搜索并替换前一行python

搜索并替换前一行python,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,在一个文件中,我有以下文本: xxxxxx PCTFREE 10 INITRANS 8 MAXTRANS 255 STORAGE ( BUFFER_POOL DEFAULT ), ) 我正在尝试搜索以(“)”开头的行,并从上一行中删除“.” 您可以逐行循环文本,并检查前面的一个索引中是否有): 输出: xxxxxx PCTFREE 10 INITRANS 8

在一个文件中,我有以下文本:

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

我正在尝试搜索以(“)”开头的行,并从上一行中删除“.”

您可以逐行循环文本,并检查前面的一个索引中是否有

输出:

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

您在描述中要求的内容与示例输入中的任何内容都不匹配,甚至与之接近。没有一行以
开头。其中一行以一些空格和a)开头,但前面的一行是空行,前面的最后一行没有要删除的逗号

但我将忽略示例输入,并解释如何执行您在描述中要求的操作

最简单的方法是在迭代行的同时跟踪上一行:

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')

通过使用类似于中的
pairwise
迭代器包装器,您可以使其更简洁、更紧凑,但稍作修改以在末尾包含“extra”对:

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')

没有一行以
开头。其中一行以一些空格和
开头,但前面的一行是空行,前面的最后一行没有逗号可删除。欢迎使用StackOverflow。请阅读,并张贴一份。你的问题开头不错,但我们看不出你具体做了什么。StackOverflow不是问“请为我写代码”的合适地方。但是如果你认真尝试并告诉我们,我们可以告诉你哪里出了问题。该文件包含不止一次这种情况,这就是为什么我有上述xxx。我无法删除所有的“,”仅删除前面的“)
str.replace
替换所有出现的内容
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')
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')