PyParsing: Is this correct use of setParseAction()?

Posted by Rosarch on Stack Overflow See other posts from Stack Overflow or by Rosarch
Published on 2010-05-31T01:55:30Z Indexed on 2010/05/31 2:02 UTC
Read the original article Hit count: 263

Filed under:
|
|
|

I have strings like this:

"MSE 2110, 3030, 4102"

I would like to output:

[("MSE", 2110), ("MSE", 3030), ("MSE", 4102)]

This is my way of going about it, although I haven't quite gotten it yet:

def makeCourseList(str, location, tokens):
    print "before: %s" % tokens

    for index, course_number in enumerate(tokens[1:]):
        tokens[index + 1] = (tokens[0][0], course_number)

    print "after: %s" % tokens

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

course_data = (course + ZeroOrMore(Suppress(',') + COURSE_NUMBER)).setParseAction(makeCourseList)

This outputs:

>>> course.parseString("CS 2110")
([(['CS', 2110], {})], {})
>>> course_data.parseString("CS 2110, 4301, 2123, 1110")
before: [['CS', 2110], 4301, 2123, 1110]
after: [['CS', 2110], ('CS', 4301), ('CS', 2123), ('CS', 1110)]
([(['CS', 2110], {}), ('CS', 4301), ('CS', 2123), ('CS', 1110)], {})

Is this the right way to do it, or am I totally off?

Also, the output of isn't quite correct - I want course_data to emit a list of course symbols that are in the same format as each other. Right now, the first course is different from the others. (It has a {}, whereas the others don't.)

© Stack Overflow or respective owner

Related posts about python

Related posts about parsing