注释文件中的行模式

Commenting a pattern of line in a file

我需要评论一组具有相似模式且具有唯一值的行。

例子

a {
1
2 one
3
}


a {
1
2 two
3
}

在上面的示例中,我需要对整个块进行注释。基于唯一值“二” 像这样。

a {
1
2 one
3
}

#a {
#1
#2 two
#3
#}

以上我能够得到带有索引行的块,但无法进行就地编辑或替换。 我正在使用 python2 代码:

line = open('file').readlines()
index = line.index('two\n')
abline = int(index)-2
beline = int(abline)+5
for linei in range(abline,beline+1):
    nline = '%s%s' % ("##",line[linei].strip())
    print(nline)

我认为您无法就地完成。您可以做的是先读取文件,注释其内容,然后写入文件。像这样

lines = open('file').readlines()

index = -1

for ind,line in enumerate(lines):
    if 'two' in line:
        index = ind 

commented_lines = ''
for ind,line in enumerate(lines):
    if ind >= index-2 and ind <=index+2:
        commented_lines += '#%s' %line
    else:
        commented_lines += line


with open('file', 'w') as f:
    f.write(commented_lines)

假设搜索到的文本将始终存在于文件中。