Last active
October 10, 2016 21:37
-
-
Save pykong/df645e04c97ab7290653b9ed05d68fd1 to your computer and use it in GitHub Desktop.
Substitute multiple patterns in string with those in a provided dictionary.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment