Skip to content

Instantly share code, notes, and snippets.

@lonetwin
Created August 17, 2021 10:16
Show Gist options
  • Save lonetwin/0dfacb414feb9eb6d97bc5a05032cc28 to your computer and use it in GitHub Desktop.
Save lonetwin/0dfacb414feb9eb6d97bc5a05032cc28 to your computer and use it in GitHub Desktop.
Transform a piece of text by appling an ordered list of string transformations to input text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from itertools import chain
from functools import reduce, partial
def apply_substitutions(text, substitutions):
"""Apply an ordered list of string transformations to input text
Given some text and a list of tuples in the form
[(<regex_pattern>, <substitution>), ....]
returns the text with all the specified substitutions performed.
"""
transforms = (partial(re.sub, p, s) for p, s in substitutions)
return reduce(lambda t, sub: sub(t), iter(transforms), text)
if __name__ == '__main__':
assert(
apply_substitutions(
'this is a xxx yyy',
(
('xxx', 'cool'),
('yyy', 'tool'),
(r'.*', lambda match: match.group().title()),
)
) == 'This Is A Cool Tool'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment