正则表达式 - 增量替换

Joe*_*oey 1 php c# python java regex

有没有办法只使用正则表达式进行整数增量替换.

这是问题所在,我的文本文件包含1 000 000行所有以%开头

我想使用正则表达式逐步替换整数#.

input:

% line one

% line two

% line three

...

output:

1 line one

2 line two

3 line three

...
Run Code Online (Sandbox Code Playgroud)

nos*_*klo 5

n = 1
with open('sourcefile.txt') as input:
    with open('destination.txt', 'w') as output:
        for line in input:
            if line.startswith('%'):
                line = str(n) + line[1:]
                n += 1
            output.write(line)
Run Code Online (Sandbox Code Playgroud)