Search code examples
pythonhaskellpyparsingparsec

acccumulate using pyparsing


I have some data that can be parsed using the OneorMore function from pyparsing. Something like,

fun = OneorMore( foo.setResultsName("foo") +  bar.setResultsname("bar") )

where bar and foo are 2 parsers.

The problem with this function is that everytime that OneorMore match foo and bar parsers in the data stream, the corresponding values associated with the keys "foo" and "bar" are updated.But, how can I accumulate all the matched values of foo and bar?

I'm trying to implement something like the many1 monadic parser in Haskell, saving the result of parsing foo and bar in an Algebraic Data type, like

data FooBar a = FooBar a a

many1 :: ParsecT s u m a -> ParsecT s u m [a]

many1 parserFooBar :: ParsecT s u m [FooBar a]

How can I do this in python?


Solution

  • I'm not 100% sure I understand what you're asking, and am rusty with pyparsing, but I think Group will help you.

    from pyparsing import *
    
    text = 'abc123xyz456def789'
    foo = Word(alphas)
    bar = Word(nums)
    fun = OneOrMore(Group(foo.setResultsName("foo") + bar.setResultsName("bar")))
    
    results = fun.parseString(text)
    
    #Print all foo
    print [r.foo for r in results]
    #Print all bar
    print [r.bar for r in results]