Python grep文件的每一行,并递增值
我有一个包含以下行的文件:Python grep文件的每一行,并递增值,python,regex,Python,Regex,我有一个包含以下行的文件: [tree]:1,"asdf" [box]:2,"yuio" [bee]:10,"rtyu" [cup]:15,"bnmv" [tree]:13,"asdf" 我希望输出是 [tree]:2,"asdf" [box]:2,"yuio" [bee]:10,"rtyu" [cup]:15,"bnmv" [tree]:14,"asdf" 所以我需要将[tree]值增加1。我需要一些方法来搜索每一行的[tree],复制它旁边可能超过2位的数字,然后增加这个数字。我已经在M
[tree]:1,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:13,"asdf"
我希望输出是
[tree]:2,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:14,"asdf"
所以我需要将[tree]值增加1。我需要一些方法来搜索每一行的[tree],复制它旁边可能超过2位的数字,然后增加这个数字。我已经在Matlab中完成了这项工作,但速度非常慢,而且需要重写整个文件。我正在寻找一个更快的替代方案,比如bash脚本或者python中的一些东西。试试这个:
def incrementKeys(infilepath, outfilepath, keys, incrementBy):
with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
for line in infile:
if any(line.startswith(key) for key in keys):
k, tail = line.split(',')
k, val = k.split(":")
val = int(val)+incrementBy
line = "%s:%d,%s\n" %(k, val, tail)
outfile.write(line)
f = file("file.txt")
for l in f:
if l[:6] == "[tree]":
s = "".join([l[:l.find(":")+1], str(int(l[l.find(":")+1:l.find(",")])+1), l[l.find(","):]])
print s
不要打印,而要对结果做任何你喜欢的事情。例如,您可以再次将其写入文件