mirror of
https://github.com/kovidgoyal/calibre.git
synced 2025-07-09 03:04:10 -04:00
Implementation of a multiple replace class based on Dict substitutions. Very fast for large dictionnaries.
This commit is contained in:
parent
69baad55fc
commit
3cf9f7986a
32
src/calibre/utils/mreplace.py
Normal file
32
src/calibre/utils/mreplace.py
Normal file
@ -0,0 +1,32 @@
|
||||
#multiple replace from dictionnary : http://code.activestate.com/recipes/81330/
|
||||
__license__ = 'GPL v3'
|
||||
__copyright__ = '2010, sengian <sengian1 @ gmail.com>'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
import re
|
||||
from UserDict import UserDict
|
||||
|
||||
class MReplace(UserDict):
|
||||
def __init__(self, dict = None):
|
||||
UserDict.__init__(self, dict)
|
||||
self.re = None
|
||||
self.regex = None
|
||||
self.compile_regex()
|
||||
|
||||
def compile_regex(self):
|
||||
if len(self.data) > 0:
|
||||
keys = sorted(self.data.keys(), key=len)
|
||||
keys.reverse()
|
||||
tmp = "(%s)" % "|".join([re.escape(item) for item in keys])
|
||||
if self.re != tmp:
|
||||
self.re = tmp
|
||||
self.regex = re.compile(self.re)
|
||||
|
||||
def __call__(self, mo):
|
||||
return self[mo.string[mo.start():mo.end()]]
|
||||
|
||||
def mreplace(self, text):
|
||||
#Replace without regex compile
|
||||
if len(self.data) < 1 or self.re is None:
|
||||
return text
|
||||
return self.regex.sub(self, text)
|
Loading…
x
Reference in New Issue
Block a user