在 PHP 中,您有 preg_replace($patterns, $replacements, $string)
,您可以在其中通过传入模式和替换数组来一次性进行所有替换。
Python 中的等价物是什么?
我注意到 string 和 re 函数 replace()
和 sub()
不接受字典...
根据 rick 的评论进行编辑以澄清:
这个想法是让一个带有键的字典被视为正则表达式模式,例如 '\d+S'
,和(希望)常量字符串值(希望没有反向引用)。现在相应地编辑我的答案(即回答实际问题)。
最佳答案
最接近的可能是:
somere.sub(lambda m: replacements[m.group()], text)
例如:
>>> za = re.compile('z\w')
>>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')
'fa BLU BLA bu'
使用 .get
而不是 []
-indexing 如果你想为 replacements
中缺失的匹配项提供默认值。
编辑:rick 真正想要的是有一个字典,其中的键被视为正则表达式模式,例如 '\d+S'
,以及(希望)常量字符串值(希望 w/o 反向引用)。食谱食谱可以为此目的进行调整:
def dict_sub(d, text):
""" Replace in 'text' non-overlapping occurences of REs whose patterns are keys
in dictionary 'd' by corresponding values (which must be constant strings: may
have named backreferences but not numeric ones). The keys must not contain
anonymous matching-groups.
Returns the new string."""
# Create a regular expression from the dictionary keys
regex = re.compile("|".join("(%s)" % k for k in d))
# Facilitate lookup from group number to value
lookup = dict((i+1, v) for i, v in enumerate(d.itervalues()))
# For each match, find which group matched and expand its value
return regex.sub(lambda mo: mo.expand(lookup[mo.lastindex]), text)
使用示例:
d={'\d+S': 'wot', '\d+T': 'zap'}
t='And 23S, and 45T, and 66T but always 029S!'
print dict_sub(d, t)
发出:
And wot, and zap, and zap but always wot!
您可以避免构建 lookup
并只使用 mo.expand(d.values()[mo.lastindex-1])
,但这可能有点慢如果 d
非常大并且有很多匹配项(抱歉,还没有对这两种方法进行精确测量/基准测试,所以这只是一个猜测;-)。
关于php - 在 Python 中替换字符串时可以传递字典吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/937697/