[56] | 1 | import re, string
|
---|
| 2 | # Taken from http://effbot.org/zone/python-replace.htm
|
---|
| 3 |
|
---|
| 4 | class MultiReplace:
|
---|
| 5 | def __init__(self, repl_dict):
|
---|
| 6 | # "compile" replacement dictionary
|
---|
| 7 |
|
---|
| 8 | # assume char to char mapping
|
---|
| 9 | charmap = map(chr, range(256))
|
---|
| 10 | for k, v in repl_dict.items():
|
---|
| 11 | if len(k) != 1 or len(v) != 1:
|
---|
| 12 | self.charmap = None
|
---|
| 13 | break
|
---|
| 14 | charmap[ord(k)] = v
|
---|
| 15 | else:
|
---|
| 16 | self.charmap = string.join(charmap, "")
|
---|
| 17 | return
|
---|
| 18 |
|
---|
| 19 | # string to string mapping; use a regular expression
|
---|
| 20 | keys = repl_dict.keys()
|
---|
| 21 | keys.sort() # lexical order
|
---|
| 22 | keys.reverse() # use longest match first
|
---|
| 23 | pattern = string.join(map(re.escape, keys), "|")
|
---|
| 24 | self.pattern = re.compile(pattern)
|
---|
| 25 | self.dict = repl_dict
|
---|
| 26 |
|
---|
| 27 | def replace(self, str):
|
---|
| 28 | # apply replacement dictionary to string
|
---|
| 29 | if self.charmap:
|
---|
| 30 | return string.translate(str, self.charmap)
|
---|
| 31 | def repl(match, get=self.dict.get):
|
---|
| 32 | item = match.group(0)
|
---|
| 33 | return get(item, item)
|
---|
| 34 | return self.pattern.sub(repl, str)
|
---|
| 35 |
|
---|
| 36 | #print r.replace("spam&eggs") # prints "eggs&spam"
|
---|
| 37 | #
|
---|
| 38 | #r = MultiReplace({"a": "b", "b": "a"})
|
---|
| 39 | #print r.replace("keaba") # "kebab"
|
---|
| 40 | #
|
---|
| 41 | #r = MultiReplace({". ": "\n", "!": "exclamation", "?": "question"})
|
---|
| 42 | #print repr(r.replace("look. an albatross !")) # 'look\nan albatross exclamation'
|
---|