Skip to content

Instantly share code, notes, and snippets.

@robertodr
Last active January 9, 2021 08:58
Show Gist options
  • Save robertodr/eb1ef083ad9b21e15203ba9d4a930fea to your computer and use it in GitHub Desktop.
Save robertodr/eb1ef083ad9b21e15203ba9d4a930fea to your computer and use it in GitHub Desktop.
try: dict
except: from UserDict import UserDict as dict
class Xlator(dict):
""" All-in-one multiple-string-substitution class """
def _make_regex(self):
""" Build re object based on the keys of the current dictionary """
return re.compile("|".join(map(re.escape, self.keys( ))))
def __call__(self, match):
""" Handler invoked for each regex match """
return self[match.group(0)]
def xlat(self, text):
""" Translate text, returns the modified text. """
return self._make_regex( ).sub(self, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment