按模式停止更换?

时间:2016-06-28 03:17:48

标签: python

说我的文件看起来像这样:

some lines
tom
some lines
beginword a b
some lines
endword
jim
some lines
beginword x y
some lines
endword
...

想成为:

some lines
tom
some lines
beginword ZZ b
some lines
endword
jim
some lines
beginword x y
some lines
endword

所以这是我的python代码:

input = open("file", "r")
output = open("file_updated", "w")
dummy = ""
item = []
for line in input:
    dummy += line
    if line.find("tom" + "\n") != -1:
        for line in input:
            if line.find("beginword") != -1:
                item = line.split()
                dummy += item[0] + " w " + item[-1] + "\n"
            else:
                dummy += line
output.write(dummy)
input.close()
output.close()

它替换所有包含" beginword"的行,包括属于" jim"的行,如何通过" endword"来停止替换?属于" tom"?

1 个答案:

答案 0 :(得分:0)

使用break声明

input = open("file", "r")
output = open("file_updated", "w")
dummy = ""
item = []
for line in input:
    dummy += line
    if line.find("tom" + "\n") != -1:
        for line in input:
            # check for endword and exit for loop  
            if line.find("endword" + "\n") == 0:
                dummy += line                    
                break

            if line.find("beginword") != -1:
                item = line.split()
                dummy += item[0] + " w " + item[-1] + "\n"
            else:
                dummy += line
output.write(dummy)
input.close()
output.close()

另外,看看这些: