不能得到pyparsing Dict()返回嵌套字典 [英] Can't get pyparsing Dict() to return nested dictionary

查看:179
本文介绍了不能得到pyparsing Dict()返回嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析表单的字符串:

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

我希望结果以嵌套字典的形式返回,即上述字符串,结果应该如下所示:

  {'foo':{'bar':'baz','x' 'y'}} 

尽管Dict()和Group()的大量组合我无法获得它工作我的(其中一个版本)的语法如下所示:

 导入pyparsing为pp 
field_name = pp.Word (pp.alphanums)
field_value = pp.Word(pp.alphanums)
colon = pp.Suppress(pp.Literal(':'))

expr = pp。 Dict(
pp.Group(
field_name + \
pp.nestedExpr(
content = pp.delimitedList(
pp.Group(field_name + colon + field_value) ,
delim =';'




现在,结果如下:

 在[62]中:str =' foo(bar:baz; x:y)'

在[63]中:expr.parseString(str).asList()
输出[63]:[['foo' ['bar','baz'],['x','y']]]]

在[64]中:expr.parseString(str).asDict()
[64]:{'foo':({(['bar','baz'],{}),(['x','y'],{})],{})}

在[65]中:print(expr.parse String(str).dump())
输出[65]:[['foo',[['bar','baz'],['x','y']]]]
- foo:[['bar','baz'],['x','y']]

所以 asList()版本对我来说看起来不错,应该产生一个我以后想要的字典。当然,给定(我明白的方式,请纠正我)Dict()将通过使用列表的第一个元素作为键来解析令牌列表,其余所有作为字典中该键的值。这在字典不嵌套的情况下起作用。例如在这种情况下:

  expr = pp.Dict(
pp.delimitedList(
pp。 Group(field_name + colon + field_value),
delim =';'



在[76]中:expr.parseString('foo:bar; baz:x').asDict()
Out [76]:{'baz':'x','foo':'bar'}
asList()并将其手动转换为字典,但我宁愿使用pyparsing做:)



谢谢。

解决方案

div>

两个问题:




  • 你缺少一个 pp.Dict pp.delimitedList 之间,使内部结果正常工作 asDict

  • 在最外层的 ParsingResult 实例中,您只调用 asDict ,留下内部 ParsingResult uninterpreted



我尝试了以下内容:

 从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),

))

然后使用它:

 >>> 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'}}


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. for the above string, the results should look like this:

{ 'foo' : { 'bar' : 'baz', 'x' : 'y' } }

Despite numerous combinations of Dict() and Group() I can't get it to work. My (one of the versions of) grammar looks like this:

import pyparsing as pp
field_name = pp.Word( pp.alphanums )
field_value = pp.Word( pp.alphanums )
colon = pp.Suppress( pp.Literal( ':' ) )

expr = pp.Dict( 
    pp.Group( 
        field_name + \
        pp.nestedExpr( 
            content = pp.delimitedList( 
                 pp.Group( field_name + colon + field_value ), 
                 delim = ';' 
            ) 
        ) 
    ) 
)

and now, the results are as follows:

In [62]: str = 'foo(bar:baz;x:y)'

In [63]: expr.parseString( str ).asList()
Out[63]: [['foo', [['bar', 'baz'], ['x', 'y']]]]

In [64]: expr.parseString( str ).asDict()
Out[64]: {'foo': ([(['bar', 'baz'], {}), (['x', 'y'], {})], {})}

In [65]: print( expr.parseString( str ).dump() )
Out[65]: [['foo', [['bar', 'baz'], ['x', 'y']]]]
         - foo: [['bar', 'baz'], ['x', 'y']]

So the asList() version looks quite good to me and should yield a dictionary I'm after I think. Of course given that (the way I understand it, please correct me) Dict() will parse lists of tokens by using the first element of the list as a key and all the rest as values of that key in a dictionary. This works insofar the dictionary is not nested. For example in such case:

expr = pp.Dict( 
    pp.delimitedList( 
        pp.Group( field_name + colon + field_value ), 
        delim = ';' 
    ) 
)

In [76]: expr.parseString( 'foo:bar;baz:x' ).asDict()
Out[76]: {'baz': 'x', 'foo': 'bar'}

So, the question is what is wrong with the first case (and my understanding of the problem) or perhaps Dict() can't cope with such case? I could use asList() and convert that manually into a dictionary, but I'd rather have pyparsing do it :)

Any help or directions would be greately appreciated.

Thank you.

解决方案

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'}}

这篇关于不能得到pyparsing Dict()返回嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆