thanks all! it's great
Trung Hoang
thoa0025 at mail.usyd.edu.au
Fri Mar 29 21:49:17 EST 2002
"Bengt Richter" <bokr at oz.net> wrote in message
news:a80oq0$av7$0 at 216.39.172.122...
> On 29 Mar 2002 02:00:03 GMT, bokr at oz.net (Bengt Richter) wrote:
> [...]
> >Here is something to deal with the key order problem (i.e., if one
> >key is a substring of another. You have to sort by length to get
> >maximal or minimal matching. This is for maximal:
> >
> > >>> def dirinterp(s,d):
> > ... import re
> > ... klist = [(-len(k),k) for k in d.keys()]
> > ... klist.sort()
> > ... resp = re.compile('('+'|'.join([k for l,k in klist])+')')
> > ... return ''.join([kv.get(w,w) for w in resp.split(s)])
> ^^--oops, that worked because of a leftover
global ;-/
> > ...
> > >>> subdir = {"sub":"<was sub>","substring":"<was substring>"}
> > >>> dirinterp("Will sub or substring be replaced?",subdir)
> > 'Will <was sub> or <was substring> be replaced?'
> > >>> dirinterp("Will substring or sub be replaced?",subdir)
> > 'Will <was substring> or <was sub> be replaced?'
> >
> >This is hardly tested at all, but I guess it could be handy.
> Must run in fresh interpreter before posting ;-/
>
> >>> from miscutil import subbydict
> >>> d={'x':'A', 'xx':'B','xxx':'C'}
> >>> s='xxxxxx xxxx xxx xx x'
> >>> subbydict(s,d)
> 'CC CA C B A'
> >>> s='xxxxxx xxxxx xxxx xxx xx x'
> >>> subbydict(s,d)
> 'CC CB CA C B A'
>
> where name changed and kv->d
>
> def subbydict(s,d):
> import re
> klist = [(-len(k),k) for k in d.keys()]
> klist.sort()
> resp = re.compile('('+'|'.join([k for l,k in klist])+')')
> return ''.join([d.get(w,w) for w in resp.split(s)])
>
> Regards,
> Bengt Richter
More information about the Python-list
mailing list