Help, Search and Substitute

Steve Holden sholden at holdenweb.com
Mon Nov 6 08:46:47 EST 2000


Greg Jorgensen wrote:
> 
[request for key substitution snipped]
> 
> I just wrote something similar to do bulk mailings from templates and merge
> files. My first version used re.sub but was too slow, but this technique is
> fast enough:
> 
> # break the template into list of chunks that are either plain text or
> {field_name}
> rx = re.compile(r'(\{[a-zA-Z0-9_]+\})')
> chunks = rx.split(template)
> 
> # values dict contains field_name: value entries, i.e.
> values = {'NAME':'Greg', 'PHONE':'503-555-1212', ....}
> 
> # look at each chunk and change {field_name} to merged value
> message = []
> for s in chunks:
>     if s and s[0] == '{' and s[-1] == '}':    # {field_name}
>         s = s[1:-1]    # strip surrounding {...}
>         s = values.get(s, s)    # get value of field_name, or field_name if
> not in merge dict
> 
>     message.append(s)
> 
> # put merged message back together
> ''.join(message)        # bizarre join syntax
> 
> print message
> 
> --
> My complete mailmerge program handles nested {...} and will recursively
> process the message until all {FIELDS} are replaced; this allows {...} to
> appear in the merge file as well as the template.
> 
In simpler cases, which do not have your requirement for nesting and
recursion, one possible optimization would be to simply replace
all "{" with "%(", and all "}" with ")s", for example turning

"This is {KEY}'s value: {VALUE}" into

"This is %(KEY)s's value: %(VALUE)s"

then you can use the "%" string formatting operator with your table as
right argument to have all the substitutions made in a single pass"

>>> "This is %(KEY)s's value: %(VALUE)s" % {"KEY": 'string', "VALUE": '3.14159'}
"This is string's value: 3.14159"

regards
 Steve

-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/





More information about the Python-list mailing list