Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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