is there an easy way to parse a nested list ?

Paul McGuire ptmcg at austin.rr.com
Mon Mar 16 10:49:58 EDT 2009


On Mar 16, 4:29 am, Vlastimil Brom <vlastimil.b... at gmail.com> wrote:
> 2009/3/16 Vlastimil Brom <vlastimil.b... at gmail.com>:
>
>
>
> > 2009/3/16 Stef Mientki <stef.mien... at gmail.com>:
> >> hello,
>
> >> I need to parse a nested list, given as a string, like this
>
> >> line = " A  [  B  [ C+2 ] + 3 ] "
>
> > ...
>
> >> thanks,
> >> Stef
>
> > there is a "nestedExpr" (and probably other options, I'm not aware of ...:-)
> > ...
> > regards
> > vbr
>
> Well, I thought, there was something already there in the examples for
> pyparsing, but couldn't find it first.
> check the selective pyparsing evaluator, which also supports lists:
>
> http://pyparsing.wikispaces.com/file/view/parsePythonValue.py
>

The OPs test cases aren't really valid Python lists, so nestedExpr
will have to do:


from pyparsing import oneOf, alphas, Word, nums, OneOrMore, nestedExpr

# an element within the list can be:
# - a single alphabetic letter
# - one of + - * or /
# - an unsigned integer
element = oneOf(list(alphas+"+-*/")) | Word(nums)

expr = OneOrMore(element |
        nestedExpr("[", "]", content=OneOrMore(element))
        )

src = " A  [  B  [ C+2 ] + 3 ] "
print expr.parseString(src)

Prints:

['A', ['B', ['C', '+', '2'], '+', '3']]

Note that this is an actual Python nested list, the []'s of the
original string have been stripped away (they aren't needed, as the
nested structure that was defined by the []'s is now represented as a
data structure with actual nesting).

Also, pyparsing is pretty forgiving about whitespace.  This same
parser, even though no whitespace is explicitly mentioned, will just
as easily parse "A[B[C+2]+3]".

-- Paul
(More pyparsing info at http://pyparsing.wikispaces.com.)



More information about the Python-list mailing list