def substitute ( dict_ , source ) : d_esc = ( re . escape ( k ) for k in dict_ . keys ( ) ) pattern = re . compile ( '|' . join ( d_esc ) ) return pattern . sub ( lambda x : dict_ [ x . group ( ) ] , source )
replace dictionary python regex
Perform re . sub with the patterns in the given dict Args : dict_ : { pattern : repl } source : str
def substitute(dict_, source):
    """ Perform re.sub with the patterns in the given dict
    Args:
      dict_: {pattern: repl}
      source: str
    """
    d_esc = (re.escape(k) for k in dict_.keys())
    pattern = re.compile('|'.join(d_esc))
    return pattern.sub(lambda x: dict_[x.group()], source)