我有一个像这样的正则表达式:
findthe = re.compile(r" the ")
replacement = ["firstthe", "secondthe"]
sentence = "This is the first sentence in the whole universe!"
我要做的是用列表中的关联替换词替换每个匹配项,以便结束语句如下所示:
>>> print sentence
This is firstthe first sentence in secondthe whole universe
我尝试在for循环中使用re.sub
枚举替换,但看起来re.sub
会返回所有匹配项。有人能告诉我如何有效地做到这一点吗?
答案 0 :(得分: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)
或类似的东西也会起作用:
import re
findthe = re.compile(r"\b(the)\b")
print re.sub(findthe, replacement[1],re.sub(findthe, replacement[0],sentence, 1), 1)
至少:
re.sub(findthe, lambda matchObj: replacement.pop(0),sentence)
答案 1 :(得分:4)
Artsiom的最后一个答案是replacement
变量的破坏性。这是一种不用清空replacement
re.sub(findthe, lambda m, r=iter(replacement): next(r), sentence)
答案 2 :(得分:2)