Last active
January 9, 2021 08:58
-
-
Save robertodr/eb1ef083ad9b21e15203ba9d4a930fea to your computer and use it in GitHub Desktop.
This file contains 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
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