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

标签 python regex

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

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/

相关文章:

javascript - 如何在innerHTML中模仿markdown替换?

regex - 日期时间格式的动态正则表达式

php - 使用正则表达式管理电话号码验证漏洞

python - numpy apply_along_axis 具有不同的结果大小

python - 使用基于字符串数组中元素的集合名称在 pymongo 中创建 MongoDB 集合

python - 将二维列表写入JSON文件

python - 在python中使用正则表达式获取特定IP

Python Pandas.Series.asof : Cannot compare type 'Timestamp' with type 'struct_time'

python - Cython 用户的 Numpy 类型

javascript - 正则表达式用于删除逗号后的单个空格