Ale*_*lli 10
最接近的可能是:
somere.sub(lambda m: replacements[m.group()], text)
Run Code Online (Sandbox Code Playgroud)
例如:
>>> za = re.compile('z\w')
>>> za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')
'fa BLU BLA bu'
Run Code Online (Sandbox Code Playgroud)
如果要为缺少的匹配提供默认值,请使用a .get而不是[]-indexing replacements.
编辑:瑞克真正想要的是有一个带有键的字典作为正则表达式模式,例如'\d+S',和(希望)常量字符串值(希望没有后向引用).食谱配方可以用于此目的:
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)
Run Code Online (Sandbox Code Playgroud)
使用示例:
d={'\d+S': 'wot', '\d+T': 'zap'}
t='And 23S, and 45T, and 66T but always 029S!'
print dict_sub(d, t)
Run Code Online (Sandbox Code Playgroud)
发出:
And wot, and zap, and zap but always wot!
Run Code Online (Sandbox Code Playgroud)
你可以避免构建lookup和使用mo.expand(d.values()[mo.lastindex-1]),但如果d非常大并且有很多匹配(这很可能,没有精确测量/基准测试两种方法,这可能只是一个猜测;-).
| 归档时间: |
|
| 查看次数: |
3452 次 |
| 最近记录: |