使用re.sub在文本中插入递增的数字

问题描述 投票:1回答:2

使用pythons re.sub函数,我想在每个匹配项中添加方括号并增加数字。

到目前为止,我的方法是一个示例:

import re

items = []
def rep(matchobj):
    items.append(matchobj.group())
    return r'[\g<1>]<' + str(len(items)) + '>'

text = 'this text and this example will give this outcome.'
text = re.sub(r'this', rep, text)
print(text)

# -> [\g<1>]<1> text and [\g<1>]<2> example will give [\g<1>]<3> outcome.

我真正想要的是:

[this]<1> text and [this]<2> example will give [this]<3> outcome.

python regex
2个回答
3
投票

您可以使用itertools.count完成任务:

itertools.count

打印:

import re
from itertools import count

text = 'this text and this example will give this outcome.'
text = re.sub(r'this', lambda g, c=count(1): f'[{g.group(0)}]<{next(c)}>', text)
print(text)

0
投票

由于要提供替换功能,因此[this]<1> text and [this]<2> example will give [this]<3> outcome. 会按原样返回字符串,因此不会像re.sub那样扩展组引用。因此,您只需要插入\g<1>。我将使用matchobj.group(),这也可以避免显式调用str.format

同样,使用str也很麻烦,因为它是隐式的非局部变量。您可以将其设置为可变的默认参数items(即rep),但是如果您只在意它的长度,请改用def rep(matchobj, items=[]):

itertools.count
© www.soinside.com 2019 - 2024. All rights reserved.