mirror of
https://github.com/Mikaela/Limnoria.git
synced 2025-01-22 01:54:09 +01:00
Add utils.str.multipleRemover.
This commit is contained in:
parent
fffccb4600
commit
fa35a07941
@ -220,11 +220,20 @@ def perlVariableSubstitute(vars, text):
|
|||||||
|
|
||||||
def multipleReplacer(dict_):
|
def multipleReplacer(dict_):
|
||||||
"""Return a function that replaces all dict keys by the associated
|
"""Return a function that replaces all dict keys by the associated
|
||||||
value."""
|
value. More efficient than multiple .replace()."""
|
||||||
dict_ = {re.escape(key): val for key,val in dict_.items()}
|
dict_ = {re.escape(key): val for key,val in dict_.items()}
|
||||||
matcher = re.compile('|'.join(dict_.keys()))
|
matcher = re.compile('|'.join(dict_.keys()))
|
||||||
return lambda x:matcher.sub(lambda m: dict_[m.group(0)], x)
|
return lambda x:matcher.sub(lambda m: dict_[m.group(0)], x)
|
||||||
|
|
||||||
|
def multipleRemover(list_):
|
||||||
|
"""Return a function that removes all words in the list. A bit more
|
||||||
|
efficient than multipleReplacer"""
|
||||||
|
list_ = [re.escape(x) for x in list_]
|
||||||
|
matcher = re.compile('|'.join(list_))
|
||||||
|
return lambda x:matcher.sub(lambda m: '', x)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def commaAndify(seq, comma=',', And='and'):
|
def commaAndify(seq, comma=',', And='and'):
|
||||||
"""Given a a sequence, returns an English clause for that sequence.
|
"""Given a a sequence, returns an English clause for that sequence.
|
||||||
|
|
||||||
|
@ -309,10 +309,14 @@ class StrTest(SupyTestCase):
|
|||||||
f = PRTR('s/^/foo/')
|
f = PRTR('s/^/foo/')
|
||||||
self.assertEqual(f('bar'), 'foobar')
|
self.assertEqual(f('bar'), 'foobar')
|
||||||
|
|
||||||
def testmultipleReplacer(self):
|
def testMultipleReplacer(self):
|
||||||
replacer = utils.str.multipleReplacer({'foo': 'bar', 'a': 'b'})
|
replacer = utils.str.multipleReplacer({'foo': 'bar', 'a': 'b'})
|
||||||
self.assertEqual(replacer('hi foo hi'), 'hi bar hi')
|
self.assertEqual(replacer('hi foo hi'), 'hi bar hi')
|
||||||
|
|
||||||
|
def testMultipleRemover(self):
|
||||||
|
remover = utils.str.multipleRemover(['foo', 'bar'])
|
||||||
|
self.assertEqual(remover('testfoobarbaz'), 'testbaz')
|
||||||
|
|
||||||
def testPReToReplacerDifferentSeparator(self):
|
def testPReToReplacerDifferentSeparator(self):
|
||||||
f = utils.str.perlReToReplacer('s#foo#bar#')
|
f = utils.str.perlReToReplacer('s#foo#bar#')
|
||||||
self.assertEqual(f('foobarbaz'), 'barbarbaz')
|
self.assertEqual(f('foobarbaz'), 'barbarbaz')
|
||||||
|
Loading…
Reference in New Issue
Block a user