mutliple search and replace
Bengt Richter
bokr at oz.net
Thu Mar 28 22:58:56 EST 2002
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