使用re.sub和函数作为repl参数:
import re
text = "blahblahblah $%word$% blablablabla $%car$%"
words = dict(word="wassup", car="toyota")
def replacement(match):
try:
return words[match.group(1)] # Lookup replacement string
except KeyError:
return match.group(0) # Return pattern unchanged
pattern = re.compile(r'\$%(\w+)\$%')
result = pattern.sub(replacement, text)
如果要在使用re.sub时传递替换表,请使用functools.partial:
import functools
def replacement(table, match):
try:
return table[match.group(1)]
except:
return match.group(0)
table = dict(...)
result = pattern.sub(functools.partial(replacement, table), text)......或实现__call__的类:
class Replacement(object):
def __init__(self, table):
self.table = table
def __call__(self, match):
try:
return self.table[match.group(1)]
except:
return match.group(0)
result = pattern.sub(Replacement(table), text)