我需要注释一组线,它有一个独特的值与类似的模式。
示例
a {
1
2 one
3
}
a {
1
2 two
3
}在上面的例子中,我需要注释整个代码块。基于唯一值"two“,如下所示。
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)发布于 2020-06-25 01:22:43
我不认为你能就地做这件事。您可以做的是首先读取文件,注释其内容,然后写入文件。像这样的东西
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)假设搜索到的文本始终存在于文件中。
https://stackoverflow.com/questions/62559706
复制相似问题