繁体   English   中英

用文本文件中的n +字符串替换字符串的每n次出现

[英]Replacing every nth occurrence of a string by n + string in text file

文本文件包含

This is line ABC XYZ. This is something. This is ABC XYZ. foo. This is ABC XYZ. foo

所需的输出是

This is line 1 ABC XYZ. This is something. This is 2 ABC XYZ. foo. This is 3 ABC XYZ. foo 

所以,问题是由n个 ABC XYZ更换ABC XYZ的第n次出现。

您可以使用列表理解

a="This is line ABC XYZ. This is something. This is ABC XYZ. foo. This is ABC XYZ. foo"
''.join([e+str(c+1)+" ABC XYZ" for c,e in enumerate(a.split("ABC XYZ"))][0:-1])+a.split("ABC XYZ.")[-1]

re.sub方法可以将函数作为第二个参数。 将有状态函数与itertools.count对象一起用作计数器。

import re, itertools

s = 'This is line ABC XYZ. This is something. This is ABC XYZ. foo. This is ABC XYZ. foo'

def enumerator():
    counter = itertools.count(1)

    return lambda m: '{} {}'.format(next(counter), m.group())

out = re.sub(r'ABC XYZ', enumerator(), s)

print(out)

函数enumerator器可用于任何模式。

输出量

This is line 1 ABC XYZ. This is something. This is 2 ABC XYZ. foo. This is 3 ABC XYZ. foo

代码

import re

text = "This is line ABC XYZ. This is something. This is ABC XYZ. foo. This is ABC XYZ. foo"
x = re.split("(ABC XYZ)",text)
c=0
for i,s in enumerate(x):
    if re.match('(ABC XYZ)',x[i]):
        c+=1
        x[i] = str(c)+' '+x[i]
x = ''.join(x)   # This is line 1 ABC XYZ. This is something. This is 2 ABC XYZ. foo. This is 3 ABC XYZ. foo

您可以使用更优化的方法来执行此操作,但这将有助于您更好地理解它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM