如何连续替换多行

时间:2019-05-25 11:41:15

标签: python

我想用其他三行将连续包含'}'的三行转换成这样:

{
{
{
aa
bbb
ccc
}
}
}

{
{
{
aa
bbb
ccc
}
}
},

对于单行替换,我这样做:

with open("in.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('}\n', '},\n'))

它工作正常。

当我尝试连续替换三行时,我这样做了

fout.write(line.replace('}\n}\n}', '}\n}\n},'))

但是它不起作用。

如何使用python正确替换几行?

2 个答案:

答案 0 :(得分:0)

您可以使用它,在替换之前将其转换为一行:

with open("in.txt", "rt") as fin:
   with open("out.txt", "wt") as fout:
      text = ''.join(fin).replace('}\n}\n}', '}\n}\n},')
      fout.write(text)

或者,如果您希望使用不同的行,则可以像这样欺骗它,但这不是很干净:

with open("in.txt", "rt") as fin:
   with open("out.txt", "wt") as fout:
      text = '_'.join(fin).replace('}\n_}\n_}', '}\n_}\n_},') # Join in one line
      for line in text.split('_')) : # Re split in different lines
          fout.write(line)

答案 1 :(得分:0)

计算开括号,并且仅在每个开括号关闭后添加逗号。

depth = 0
with open("in.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            line = line.rstrip()

            if line == "{":
                depth += 1
            elif line == "}":
                depth -= 1

            if depth == 0 and line == "}":
                fout.write(line + ",\n")
            else:
                fout.write(line + "\n")