spock
10/10/2016 - 9:37 PM

Substitute multiple patterns in string with those in a provided dictionary.

Substitute multiple patterns in string with those in a provided dictionary.

import re

def multisub(dict, text):
    # Create a regular expression  from the dictionary keys
    regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys())))
    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)