mirror of
https://github.com/Mikaela/Limnoria.git
synced 2025-01-03 16:52:34 +01:00
Add utils.str.multipleReplacer.
This commit is contained in:
parent
59b9ba2cf8
commit
fffccb4600
@ -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.
|
||||
|
||||
|
@ -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')
|
||||
|
Loading…
Reference in New Issue
Block a user