Can't get pyparsing Dict() to return nested dictionary

后端 未结 1 1199
深忆病人
深忆病人 2021-01-04 06:17

I\'m trying to parse strings of the form:

\'foo(bar:baz;x:y)\'

I\'d like the results to be returned in form of a nested dictionary, i.e. fo

相关标签:
1条回答
  • 2021-01-04 06:45

    Two problems:

    • You are missing a pp.Dict around pp.delimitedList to make asDict on the inner result work correctly
    • You are only calling asDict on the outermost ParsingResult instance, leaving the inner ParsingResult "uninterpreted"

    I tried the following:

    from pyparsing import *
    field_name = field_val = Word(alphanums)
    colon = Suppress(Literal(':'))
    
    expr = Dict(Group(
        field_name +
        nestedExpr(content =
            Dict(delimitedList( 
                Group(field_name + colon + field_value), 
                delim = ';' 
            ))
        )
    ))
    

    Then used it like this:

    >>> res = expr.parseString('foo(bar:baz;x:y)')
    >>> type(res['foo'])
    <class 'pyparsing.ParseResults'>
    >>> { k:v.asDict() for k,v in res.asDict().items() }
    {'foo': {'x': 'y', 'bar': 'baz'}}
    
    0 讨论(0)
提交回复
热议问题