我有一个像这样的正则表达式:
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
返回所有出现的地方。谁能告诉我如何有效地做到这一点?
最佳答案
如果不需要使用正则表达式,可以尝试使用以下代码:
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)
关于python - 用不同的词替换每个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6688581/