用不同的单词替换每个匹配

Leg*_*end 8 python regex

我有一个像这样的正则表达式:

findthe = re.compile(r" the ")
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"
Run Code Online (Sandbox Code Playgroud)

我想要做的是用列表中的相关替换单词替换每个匹配项,以便结束语句如下所示:

>>> print sentence
This is firstthe first sentence in secondthe whole universe
Run Code Online (Sandbox Code Playgroud)

我尝试re.sub在for循环中使用枚举替换,但它看起来像re.sub返回所有出现.有人能告诉我如何有效地做到这一点吗?

Art*_*nka 6

如果不需要使用regEx,则可以尝试使用以下代码:

replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"

words = sentence.split()

counter = 0
for i,word in enumerate(words):
    if word == 'the':
        words[i] = replacement[counter]
        counter += 1

sentence = ' '.join(words)
Run Code Online (Sandbox Code Playgroud)

或者像这样的东西也会起作用:

import re
findthe = re.compile(r"\b(the)\b")
print re.sub(findthe, replacement[1],re.sub(findthe, replacement[0],sentence, 1), 1)
Run Code Online (Sandbox Code Playgroud)

至少:

re.sub(findthe, lambda matchObj: replacement.pop(0),sentence)
Run Code Online (Sandbox Code Playgroud)


Joh*_*ooy 5

Artsiom的最后答案是破坏性的replacement变量。这是一种不清空的方式replacement

re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence)
Run Code Online (Sandbox Code Playgroud)