Parsing a dictionary from a format string

Tim Johnson tim at johnsons-web.com
Mon Jun 20 18:39:06 EDT 2011


* Tim Johnson <tim at johnsons-web.com> [110620 13:00]:
> 
> I think later today, I will run some time tests using the `re'
> module as well as your function and the one above.
OK: Functions follow:
def grabBetween(src,begin,end):
    """Grabs sections of text between `begin' and `end' and returns a list of 
0 or more sections of text."""  
    parts = src.split(begin)
    res = []
    for part in parts: 
        L = part.split(end) 
        if len(L) > 1:
            res.append(L[0])
    return res          
def splitExtractDict(src,default):
    """Extract dictionary keys for a format string using 
`grabBetween', which uses the `split' string method."""
    D = {}
    keys = grabBetween(src,'{','}')
    for k in keys :
        D[k] = default
    return D
def reExtractDict(src,default):
    """Extract dictionary keys for a format string using `re'"""
    D = {}
    keys = re.findall(r'\{([^}]*)\}', src)
    for k in keys :
        D[k] = default
    return D
## From Hans Mulder
def findExtractDict(src,default):
    start = -1
    keys,D = [],{}
    while True:
        start = src.find('{', start+1)
        if start == -1:
            break
        end = src.find('}', start)
        if end > start:
            keys.append(src[start+1:end])
    for k in keys :
        D[k] = default
    return D
###################################################
Now here are results using a small file and a lot of
reps for each function call, just to give some meaningful
times.
###################################################
  Using `split' : 0.0309112071991
Using `re.find' : 0.0205819606781
   Using `find' : 0.0296318531036
I will note that the last method did not produce
correct results, but I also note that Hans did not
promise tested code :).
It is reasonable to suppose the `re' provides the
faster method.
 
cheers
-- 
Tim 
tim at johnsons-web dot com or akwebsoft dot com
http://www.akwebsoft.com



More information about the Python-list mailing list