split parameter line with quotes

Paul McGuire ptmcg at austin.rr.com
Fri Jan 11 15:20:25 EST 2008


On Jan 11, 12:50 pm, teddyber <teddy... at gmail.com> wrote:
> Hello,
>
> first i'm a newbie to python (but i searched the Internet i swear).
> i'm looking for some way to split up a string into a list of pairs
> 'key=value'. This code should be able to handle this particular
> example string :
>
> qop="auth,auth-int,auth-conf",cipher="rc4-40,rc4-56,rc4,des,
> 3des",maxbuf=1024,charset=utf-8,algorithm=md5-sess
>
> i know i can do that with some regexp (i'm currently trying to learn
> that) but if there's some other way...
>
> thanks

Those quoted strings sure are pesky when you try to split along
commas.  Here is a solution using pyparsing - note the argument field
access methods at the bottom.  Also, the parse action attached to
integer will do conversion of the string to an int at parse time.

More info on pyparsing at http://pyparsing.wikispaces.com.

-- Paul

from pyparsing import Word, nums, alphas, quotedString, \
    delimitedList, Literal, CharsNotIn, Dict, Group, \
    removeQuotes

arg = '''qop="auth,auth-int,auth-conf",
         cipher="rc4-40,rc4-56,rc4,des,3des",
         maxbuf=1024,charset=utf-8,algorithm=md5-sess'''

# format is: delimited list of key=value groups, where value is
#   a quoted string, an integer, or a non-quoted string up to the
next
#   ',' character
key = Word(alphas)
EQ = Literal("=").suppress()
integer = Word(nums).setParseAction(lambda t:int(t[0]))
quotedString.setParseAction(removeQuotes)
other = CharsNotIn(",")
val = quotedString | integer | other

# parse each key=val arg into its own group
argList = delimitedList( Group(key + EQ + val) )
args = argList.parseString(arg)

# print the parsed results
print args.asList()
print

# add dict-like retrieval capabilities, by wrapping in a Dict
expression
argList = Dict(delimitedList( Group(key + EQ + val) ))
args = argList.parseString(arg)

# print the modified results, using dump() (shows dict entries too)
print args.dump()

# access the values by key name
print "Keys =", args.keys()
print "cipher =", args["cipher"]

# or can access them like attributes of an object
print "maxbuf =", args.maxbuf


Prints:

[['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des,
3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5-
sess']]

[['qop', 'auth,auth-int,auth-conf'], ['cipher', 'rc4-40,rc4-56,rc4,des,
3des'], ['maxbuf', 1024], ['charset', 'utf-8'], ['algorithm', 'md5-
sess']]
- algorithm: md5-sess
- charset: utf-8
- cipher: rc4-40,rc4-56,rc4,des,3des
- maxbuf: 1024
- qop: auth,auth-int,auth-conf
Keys = ['maxbuf', 'cipher', 'charset', 'algorithm', 'qop']
maxbuf = 1024
cipher = rc4-40,rc4-56,rc4,des,3des



More information about the Python-list mailing list