在python中替换模式之后的多行?

时间:2016-09-21 14:30:17

标签: python python-2.7

我想写一个python脚本来替换我的模式之后的多行中的第一个单词,到现在我只能在我的模式后替换1行,它怎么能替换更多的行?让我们说3行。

lines.txt(输入文件,模式"第2和第34条;):

section 1
line 1
line 2
line 3
line 4
endsection
section 2
line 1
line 2
line 3
line 4
endsection
section 3
line 1
line 2
line 3
line 4
endsection

lines_mod.txt(我当前代码的结果):

section 1
line 1
line 2
line 3
line 4
endsection
section 2
mod 1
line 2
line 3
line 4
endsection
section 3
line 1
line 2
line 3
line 4
endsection

这是我的python脚本:

with open('E:/lines.txt') as fin, open('E:/lines_m.txt', 'w') as fout:
    flag = 0
    for line in fin:
        if flag == 1:
            mod_line = 'mod ' + line.split()[-1] + '\n'
            fout.write(mod_line)
            flag = 0
            continue
        fout.write(line)
        if line.find('section 2') != -1:
            flag = 1

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

list_of_words_to_replace = ['mod','apple','xxx']
with open('E:/lines.txt') as fin, open('E:/lines_mod.txt', 'w') as fout:
    flag = 0
    counter = 0  # <<<<------- added a counter 
    for line in fin:
        if flag == 1:
            counter += 1 #<<<<-------- increasing counter by one every time it loops
            mod_line = list_of_words_to_replace[counter-1] + line.split()[-1] + '\n'  #<---- changed 'mod' to a list of words to replaced.... yes  I know it's counter - 1 because we made counter start at 1 before counting and list index starts at 0 
            fout.write(mod_line)
            if counter > 3: #replaces 3 lines you can replace the number 3 with however many lines you want to override. 
                flag = 0
            continue
        fout.write(line)
        if line.find('section 2') != -1:
            flag = 1
            counter = 0 #<<<<--------- just in case you want to find anotehr section

喜欢在评论中说。你在一条令牌之后转了flag = 0,所以我们现在有一个计数器,它计算你要写多少行,当它过去时它设置flag = 0

还有其他问题吗?

答案 1 :(得分:0)

您需要重新审视您的标记更新条件以匹配预期的输出。

由于您为flag = 1条件设置了if line.find('section 2') != -1,因此它只会修改匹配行后面的一行。

由于您提到要更换更多行,您可以添加一个计数器来跟踪自flag = 1以来您已修改过的行数...当您达到所需的行数时,然后重置flag = 0

count = 0

for line in fin:
    if flag == 1 and count < 3:
        mod_line = 'mod ' + line.split()[-1] + '\n'
        count += 1
        fout.write(mod_line)
        continue