Skip to content

Instantly share code, notes, and snippets.

@MaddoxRauch
Created December 7, 2021 02:35
Show Gist options
  • Save MaddoxRauch/9628d41f408743809238392ebae53f96 to your computer and use it in GitHub Desktop.
Save MaddoxRauch/9628d41f408743809238392ebae53f96 to your computer and use it in GitHub Desktop.
Replace multiple words with new words. Parameters are the text to be edited and dictionary of words to be replaced dictionary names are replaced with corresponding values.
import re
def multiword_replace(text, word_dict):
"""Replaces multiple words using dictionary. Dictionary names found are replaced with their corresponding values."""
rc = re.compile('|'.join(map(re.escape, word_dict)))
def translate(match):
return word_dict[match.group(0)]
return rc.sub(translate, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment