From fffccb46008c4afd3813f04e0091d5f1a5fbdc80 Mon Sep 17 00:00:00 2001 From: Valentin Lorentz Date: Fri, 3 Aug 2012 09:39:31 +0200 Subject: [PATCH] Add utils.str.multipleReplacer. --- src/utils/str.py | 7 +++++++ test/test_utils.py | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/src/utils/str.py b/src/utils/str.py index 79ecb3851..56e3aaebb 100644 --- a/src/utils/str.py +++ b/src/utils/str.py @@ -218,6 +218,13 @@ def perlVariableSubstitute(vars, text): return '$' + unbraced return _perlVarSubstituteRe.sub(replacer, text) +def multipleReplacer(dict_): + """Return a function that replaces all dict keys by the associated + value.""" + dict_ = {re.escape(key): val for key,val in dict_.items()} + matcher = re.compile('|'.join(dict_.keys())) + return lambda x:matcher.sub(lambda m: dict_[m.group(0)], x) + def commaAndify(seq, comma=',', And='and'): """Given a a sequence, returns an English clause for that sequence. diff --git a/test/test_utils.py b/test/test_utils.py index da94678e6..5baa35fcf 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -309,6 +309,10 @@ class StrTest(SupyTestCase): f = PRTR('s/^/foo/') self.assertEqual(f('bar'), 'foobar') + def testmultipleReplacer(self): + replacer = utils.str.multipleReplacer({'foo': 'bar', 'a': 'b'}) + self.assertEqual(replacer('hi foo hi'), 'hi bar hi') + def testPReToReplacerDifferentSeparator(self): f = utils.str.perlReToReplacer('s#foo#bar#') self.assertEqual(f('foobarbaz'), 'barbarbaz')