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

2024-10-01 04:52:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我要做的是用列表中的一个相关的替换词替换每次出现的情况,这样结尾的句子看起来像这样:

^{pr2}$

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


Tags: theinreis情况thissentencefirst
3条回答

可以使用回调函数作为替换参数,请参见如何在:

http://docs.python.org/library/re.html#re.sub

然后使用一些计数器并根据计数器值进行更换。在

{artm>的最后一个变量是破坏性的。这里有一种不清空replacement的方法

re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence)

如果不需要使用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)

或者类似这样的方法也会起作用:

^{pr2}$

至少:

re.sub(findthe, lambda matchObj: replacement.pop(0),sentence)

相关问题 更多 >