The fundamentals...
Fredrik Lundh
fredrik at effbot.org
Fri Jan 26 12:11:53 EST 2001
"mspiggie at my-deja.com" wrote:
> I have been trying to find a way to use replace() to perform more than
> one replacement within a given file. For instance, suppose I needed to
> replace ". " with "\n", but also need to replace "!" with "exclamation"
> and "?" with "question". I have tried several approaches to this, but
> none of my neophyte ideas have produced satisfying results.
here's one way to do it:
http://www.deja.com/=dnc/getdoc.xp?AN=672888429
import re, string
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 # cannot use translate
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
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)
r = MultiReplace({"spam": "eggs", "spam": "eggs"})
print r.replace("spam&eggs")
r = MultiReplace({"a": "b", "b": "a"})
print r.replace("keaba")
r = MultiReplace({". ": "\n", "!": "exclamation", "?": "question"})
print repr(r.replace("look. an albatross !"))
Cheers /F
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list