Discussion:
[Pyparsing] Access nested ParseResults
thomas_h
2012-08-16 13:03:01 UTC
Permalink
Hi,

sorry if this is a trivial or often answered question, but I didn't find a
solution so far.
(pyparsing.__version__: 1.5.5)

I want to access nested ParseResults. Here is a simple example. (My
original problem is in a larger grammar, so please refrain from trivial
re-writes :):

import pyparsing as py

pp1=py.Word(py.alphanums)("name") + py.Word(py.nums)("number")
pp2 = py.delimitedList(pp1)("list")

r2=pp2.parseString("BAR 10, ZAP 20")

I want to access the individual "name"s and "number"s of the pp1 parses. If
you just repr(r2), it's all there, part. you can see all those names and
numbers:

In [182]: repr(r2)
Out[182]: "(['BAR', '10', 'ZAP', '20'], {'list': [((['BAR', '10', 'ZAP',
'20'], {'name': [('BAR', 0), ('ZAP', 2)], 'number': [('10', 1), ('20',
3)]}), 0)], 'name': [('BAR', 0), ('ZAP', 2)], 'number': [('10', 1), ('20',
3)]})"

But when I want to access the individual ParseResults, I can't:

In [187]: r2.list
Out[187]: (['BAR', '10', 'ZAP', '20'], {'name': [('BAR', 0), ('ZAP', 2)],
'number': [('10', 1), ('20', 3)]})

In [188]: r2.list.name
Out[188]: 'ZAP'

In [189]: r2.list.name[0]
Out[189]: 'Z'

In [190]: type(r2.list.name)
Out[190]: str

Everytime I try to access the "name" or "number" elements, they are treated
as if it's only the last value.

What am I missing?

Thomas
p***@austin.rr.com
2012-08-16 18:28:09 UTC
Permalink
thomas_h
2012-08-18 18:39:07 UTC
Permalink
Paul,

great, thanks. I was thinking briefly of the Group class during my
research, but looking at the documentation thought it might serve a
different purpose. I will re-check the material on Group.

Cheers,
Thomas
Post by unknown
pp1=py.Group(py.Word(py.alphanums)("name") + py.Word(py.nums)("number"))
r2=pp2.parseString("BAR 10, ZAP 20")
print pair.name, pair.number
print r2.list[0].name
-- Paul
unknown
1970-01-01 00:00:00 UTC
Permalink
To keep the different names of each pair separate, you'll need to enclose pp1 in a Group:

pp1=py.Group(py.Word(py.alphanums)("name") + py.Word(py.nums)("number"))


Now when you parse your string, r2.list will contain a list of paired name-values:

r2=pp2.parseString("BAR 10, ZAP 20")

for pair in r2.list:
print pair.name, pair.number

To get at an individual element, just using sliced indexing, just like it was a normal list:

print r2.list[0].name

-- Paul
Loading...