import re, string # Taken from http://effbot.org/zone/python-replace.htm class MultiReplace: def __init__(self, repl_dict): # "compile" replacement dictionary # assume char to char mapping charmap = map(chr, range(256)) for k, v in repl_dict.items(): if len(k) != 1 or len(v) != 1: self.charmap = None break charmap[ord(k)] = v else: self.charmap = string.join(charmap, "") return # string to string mapping; use a regular expression keys = repl_dict.keys() keys.sort() # lexical order keys.reverse() # use longest match first pattern = string.join(map(re.escape, keys), "|") self.pattern = re.compile(pattern) self.dict = repl_dict def replace(self, str): # apply replacement dictionary to string if self.charmap: return string.translate(str, self.charmap) def repl(match, get=self.dict.get): item = match.group(0) return get(item, item) return self.pattern.sub(repl, str) #print r.replace("spam&eggs") # prints "eggs&spam" # #r = MultiReplace({"a": "b", "b": "a"}) #print r.replace("keaba") # "kebab" # #r = MultiReplace({". ": "\n", "!": "exclamation", "?": "question"}) #print repr(r.replace("look. an albatross !")) # 'look\nan albatross exclamation'