Re: [Pyparsing] Parsing multiple items into the same Dict
Brought to you by:
ptmcg
From: Paul M. <pa...@al...> - 2006-10-24 14:00:33
|
> -----Original Message----- > From: pyp...@li... > [mailto:pyp...@li...] On > Behalf Of George Pantazopoulos > Sent: Monday, October 23, 2006 11:31 PM > To: pyp...@li... > Subject: [Pyparsing] Parsing multiple items into the same Dict > > > Hi all, > Given the following: > > s = \ > """ > a.clk = "----____----____" > a.rst = "--------________" > > b.clk = "____----____----" > b.x = "________--------" > """ > > TIMING_SPEC = OneOrMore(Regex('[-_]')) > GROUPNAME = Word(alphanums) + Suppress('.') > SIGNAME = Word(alphanums) + Suppress('=') > > GRAMMAR = ??? > > # -------- > > What would the grammar have to look like so I can get the > following kind of parse results? > George - Is it really necessary to create the dict directly in the ParseResults? This could probably be done in some tricky parse actions, but things might be simpler if your ParseResults just reflect the expression structure, and then walk the structure to build up your nested dict. Below is one way. -- Paul from pyparsing import * s = \ """ a.clk = "----____----____" a.rst = "--------________" b.clk = "____----____----" b.x = "________--------" """ TIMING_SPEC = Combine('"' + Word('_-') + '"' ) ident = Word(alphas, alphanums) SIGNAL_DEF = ident.setResultsName("GROUP") + \ '.' + ident.setResultsName("SIGNAME") + \ '=' + \ TIMING_SPEC.setResultsName("TIMING_SPEC") GRAMMAR = OneOrMore( Group(SIGNAL_DEF) ) results = GRAMMAR.parseString(s) d = {} for toks in results: if toks.GROUP not in d: d[toks.GROUP] = {} d[toks.GROUP][toks.SIGNAME] = toks.TIMING_SPEC print d print d.keys() for k in d.keys(): print k, d[k].keys() Prints out: {'a': {'rst': '"--------________"', 'clk': '"----____----____"'}, 'b': {'x': '"________--------"', 'clk': '"____----____----"'}} ['a', 'b'] a ['rst', 'clk'] b ['x', 'clk'] d['a']['rst'] -> "--------________" d['a']['clk'] -> "----____----____" d['b']['x'] -> "________--------" d['b']['clk'] -> "____----____----" -- Paul |