views:

61

answers:

1

I think I'm making a mistake in how I call setResultsName():

from pyparsing import *

DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code")
COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number")

COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0]))

course = DEPT_CODE + COURSE_NUMBER

course.setResultsName("course")

statement = course

From IDLE:

>>> myparser import *
>>> statement.parseString("CS 2110")
(['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})

The output I hope for:

>>> myparser import *
>>> statement.parseString("CS 2110")
(['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})

Does setResultsName() only work for terminals?

+4  A: 

If you change the definition of course to

course = (DEPT_CODE + COURSE_NUMBER).setResultsName("Course")

you get the following behavior:

x=statement.parseString("CS 2110")
print(repr(x))
# (['CS', 2110], {'Course': [((['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}), 0)], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]})
print(x['Dept Code'])
# CS
print(x['Course Number'])
# 2110
print(x['Course'])
# ['CS', 2110]

That's not exactly the repr you wanted, but does it suffice?

Note, from the docs:

[setResultsName] returns a copy of the original ParserElement object; this is so that the client can define a basic element, such as an integer, and reference it in multiple places with different names.

So course.setResultsName("Course") does not work because it doesn't affect course. You would instead have to say course=course.setResultsName("Course"). That's an alternative way to do what I did above.

unutbu
What does `repr()` do?
Rosarch
Also, it appears that `setResultsName()` returns a copy, but `setParseAction()` does not - why the inconsistency? Or am I mistaken?
Rosarch
@Rosarch: `repr()` returns a string representation of the object. It often gives a more complete view of the data inside an object than `str()`. I think you are right that `setParseAction` returns `self`, while `setResultName` returns a copy. I'm not knowledgable enough to explain why it is this way.
unutbu