parse lines to name value pairs

Paul McGuire ptmcg at austin.rr.com
Mon Feb 28 01:07:01 EST 2005


Damned cut-and-paste in GoogleGroups edit window (leading '.'s are to
retain spacing):

.# get pyparsing at http://pyparsing.sourceforge.net
.
.from pyparsing import quotedString, printables, Word, OneOrMore,
Forward, Literal,delimitedList,Group
.
.line1 = """path {{data/tom} C:/user/john}"""
.line2 = """books{{book music red} {book {math 1} blue} {book {tom's
book} green}}"""
.
.lbrace = Literal("{").suppress()
.rbrace = Literal("}").suppress()
.listDef = Forward()
.
.nonbracechars = "".join([ c for c in printables if c not in "{}"])
.
.# add more things to listItem, such as integers, etc. if your list has
other than quoted strings
.listItem = OneOrMore(Word(nonbracechars)) | quotedString | listDef
.
.print "With grouping"
.listDef << lbrace + Group( OneOrMore(listItem) ) + rbrace
.lineDef = Word(nonbracechars) + Group(listDef)
.
.for testdata in (line1, line2):
.    print lineDef.parseString(testdata).asList()
.
.print
.
.print "Without grouping"
.listDef << lbrace + ( OneOrMore(listItem) ) + rbrace
.lineDef = Word(nonbracechars) + Group(listDef)
.
.for testdata in (line1, line2):
.    print lineDef.parseString(testdata).asList()
.

Gives this output:

With grouping
['path', [[['data/tom'], 'C:/user/john']]]
['books', [[['book', 'music', 'red'], ['book', ['math', '1'], 'blue'],
['book', ["tom's", 'book'], 'green']]]]

Without grouping
['path', ['data/tom', 'C:/user/john']]
['books', ['book', 'music', 'red', 'book', 'math', '1', 'blue', 'book',
"tom's", 'book', 'green']]




More information about the Python-list mailing list