Help, Search and Substitute

Alex Martelli aleaxit at yahoo.com
Thu Nov 2 19:08:21 EST 2000


"Pete Shinners" <pete at visionart.com> wrote in message
news:8tcp98$t79$1 at la-mail4.digilink.net...
> 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?

Regular expressions are one approach to this, yes.  There
may be several other approaches that eschew RE's, though,
based on directly processing strings instead.

One way, based on looping through your keynames and
substituting the appropriate string whenever a keyname
appears in braces, I see has already been suggested.  The
alternative is to loop through the string looking for open
braces and closed braces, extracting each content of an
open/closed pair and trying to use it as a key; that may
indeed be handier with RE's, but RE's are not an 'absolute
must' for it.

Suppose you can rely on 'good brace placement' (i.e.,
need not try to validate the input file).  Then, maybe
(warning, untested code!):

template=open('template.txt').read()
openbrace=[i for i in len(template) where template[i]=='{']
closebrace=[i for i in len(template) where template[i]=='}']
if len(openbrace) != len(closebrace):
    raise ValueError, "Invalid template file (brace count)"
before=[template[cls+1:opn]
    for opn,cls in zip(openbrace,[-1]+closebrace)]
inside=[dic.get(template[opn+1:cls],'????')
    for opn,cls in zip(openbrace,closebrace)]
return ''.join([bef+ins for bef,ins in zip(before,inside)]) +
    template[closebrace[-1]+1:]

It's likely that a RE-based solution can be more concise,
clearer, and probably speedier, but it's not _indispensable_
to go to RE's for this...

> i assume it's time i sit down and get the basics on these?

It might not be a bad investment of your time, yes!

With re's, this may suffice... (again, untested!):

    return re.sub('{[^}]+}',myrepl,template)

where you have previously defined:

def myrepl(match):
    return dic.get(match.group(0)[1:-1], '????')


Alex






More information about the Python-list mailing list