3

I'm having trouble getting setResultsName to work for me in this script, even when attempting to emulate examples given. I've looked to the documentation, consulted the author's book, and looked at forum examples. I've tried several variations, and I'm frankly a little stumped, though I'm sure there's something silly that I'm doing wrong as I'm not very experienced at this.

from pyparsing import *

lineId = Word(nums)
topicString = Word(alphanums+'-'+' '+"'")
expr = Forward()
full_entry = Group(lineId('responsenumber') + expr)

def new_line():
    return '\n' + lineId.responsenumber # <-- here is the line that causes the error

expr << topicString + Optional(nestedExpr(content=delimitedList(expr))) + Optional((Literal(';').setParseAction(new_line) + expr))


for line in input:
    inputParseResults = delimitedList(full_entry).parseString(line).asList()
    print inputParseResults

What this portion of the code is attempting to do is to take this input:

1768    dummy data; things
27483   other things

And have it break the line at the semicolon, attach the lineId again, and then re-associate it as you see on this line:

1768    dummy data
1768    things
27483   other things

There is other code to handle formatting the output that I've not shown here; my main obstacle is getting the line break + lineId, and I think if I could get setResultsName to work, I might be set.

2 Answers 2

1

Pass the parsed tokens into your parse action like this, and access results names against the tokens, not against the parser expressions:

def new_line(tokens): 
    return '\n' + tokens.responsenumber
9
  • Thank you, Paul. Sorry to be cutting my teeth on your module. When I make the suggested change, the \n shows up but the lineID does not. Were you just giving me a clue or should I now be getting the desired result?
    – Charles W
    Commented Apr 27, 2012 at 22:00
  • 2
    Just a clue - add this line to the beginning of new_line: print tokens.dump() I think you have an extra level of nesting because of the Group, if so, try tokens[0].responsenumber instead. In truth, tho, your grammar seems really overcomplicated, I see no reason for a recursive Forward definition, for instance.
    – PaulMcG
    Commented Apr 27, 2012 at 22:27
  • The example data I have here is much simpler than what the grammar has to parse. I simplified it here to allow the focus to be on the problem I'm having. You actually helped me with formulating the grammar on a question I asked recently: stackoverflow.com/questions/10234387/… When I 'print tokens.dump()' it only gives me a semicolon, which makes sense if I'm feeding it the token that it's acting on. What I was actually hoping to do is something that mirrors what you've done on the chemistry formula example with element weights.
    – Charles W
    Commented Apr 28, 2012 at 3:11
  • Specifically, in the chem example, you define attributes of element elementRef = Group( element("symbol") + Optional( integer, default=1 )("qty") ) - so that later you can reference those parse result elements in your calculation of element and molecule weights: mw = sum( [ atomicWeight[element.symbol]*element.qty for element in formulaData ] ) I'm similarly trying to capture that id number so I can insert it again after making the new line.
    – Charles W
    Commented Apr 28, 2012 at 3:24
  • 1
    I think SO actually frowns on long comment chains on questions and answers, so maybe the wiki is better. Post to the Discussion tab on the wiki home page. FYI, asList() converts a ParseResults down to simple nested list of tokens, so you can pass it to routines that strictly expect lists, like pprint, but this strips away all named results. People like asList() because the output is cleaner-looking; a ParseResults printed out shows the nested list plus a dict of the results names. But you can access ParseResults like a list anyway, so I'm surprised that removing asList() breaks other code.
    – PaulMcG
    Commented Apr 28, 2012 at 8:26
1

Using setParseAction and forward are both things that can make my head hurt (that's how I know the code will be unreadable next time I look at it).

For what you described, delimitedList was a good choice. Unless you really needed a parse action for other magic, how about just:

from pyparsing import *

topicParser = Word(nums)("line") + \
              delimitedList(Word(alphanums+'-'+' '+"'"),';')("list")

for line in input:
    topics = topicParser.parseString(line)
    lineid = topics['line']
    for topic in topics['list']:
        print "{0} {1}".format(lineid,topic)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.