Skip to content

Instantly share code, notes, and snippets.

@howardhamilton
Created May 23, 2016 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howardhamilton/7dc0cb68e18c4b7325956c442211c97d to your computer and use it in GitHub Desktop.
Save howardhamilton/7dc0cb68e18c4b7325956c442211c97d to your computer and use it in GitHub Desktop.
Apply regex patterns and substitutions to text with a map
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