Help, Search and Substitute

andy47 at my-deja.com andy47 at my-deja.com
Thu Nov 2 22:14:13 EST 2000


In article <WClM5.4032$jv2.460427 at newsc.telia.net>,
  "Fredrik Lundh" <fredrik at effbot.org> wrote:
> Pete Shinners wrote:
> > I've got to write a search and replace type routine that
> > works on a template file. i have a dictionary with string
> > keys and values. i want parse a template file and replace
> > "{KEYNAME}" with the value of KEYNAME from my dictionary.
> >
> > i'm guessing this is where the reg-exp's come in to play?
> > i assume it's time i sit down and get the basics on these?
>
> # based on re-example-5.py
> # from (the eff-bot guide to) The Python Standard Library
> # http://www.pythonware.com/people/fredrik/librarybook.htm
>
> import re
> import string
>
> symbol_map = { "foo": "FOO", "bar": "BAR" }
>
> def symbol_replace(match, get=symbol_map.get):
>     return get(match.group(1), "")
>
> symbol_pattern = re.compile(
>     "\{(" + string.join(map(re.escape, symbol_map.keys()), "|") + ")
\}"
>     )
>
> print symbol_pattern.sub(symbol_replace, "{foo}fie{bar}")
>
> </F>

Folks,

I'm probably being really dumb here. I can see that the above works,
and I've got a vague idea of how it works but the detail is escaping
me. Can anyone explain how it works in words of one syllable to us
newbies? In particular, I'm a little lost as to how the function
symbol_replace works.

thanks-in-advance,
Andy


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list