Created
May 23, 2016 12:38
-
-
Save howardhamilton/7dc0cb68e18c4b7325956c442211c97d to your computer and use it in GitHub Desktop.
Apply regex patterns and substitutions to text with a map
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
class RegexpReplacer(object): | |
""" | |
Take in list or dictionary of regex patterns and substitutes, and apply them to text with a map. | |
""" | |
def __init__(self, patterns): | |
if type(patterns) is dict: | |
self.patterns = [(re.compile(r"{}".format(regex)), patterns['replace']) | |
for regex in patterns['pattern']] | |
else: | |
self.patterns = [(re.compile(r"{}".format(regex)), repl) for (regex, repl) in patterns] | |
def _map(self, text): | |
for pattern, repl in self.patterns: | |
(text, count) = re.subn(pattern, repl, text) | |
return text | |
def replace(self, text): | |
return self._map(text.lower()).upper() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment