python - pyparsing 的嵌套字典输出

标签 python pyparsing s-expression

我正在使用 pyparsing解析以下形式的表达式:

"and(or(eq(x,1), eq(x,2)), eq(y,3))"

我的测试代码是这样的:

from pyparsing import Word, alphanums, Literal, Forward, Suppress, ZeroOrMore, CaselessLiteral, Group

field = Word(alphanums)
value = Word(alphanums)
eq_ = CaselessLiteral('eq') + Group(Suppress('(') + field + Literal(',').suppress() + value + Suppress(')'))
ne_ = CaselessLiteral('ne') + Group(Suppress('(') + field + Literal(',').suppress() + value + Suppress(')'))
function = ( eq_ | ne_ )

arg = Forward()
and_ = Forward()
or_ = Forward()

arg << (and_ | or_ |  function) + Suppress(",") + (and_ | or_ | function) + ZeroOrMore(Suppress(",") + (and_ | function))

and_ << Literal("and") + Suppress("(") + Group(arg) + Suppress(")")
or_ << Literal("or") + Suppress("(") + Group(arg) + Suppress(")")

exp = (and_ | or_ | function)

print(exp.parseString("and(or(eq(x,1), eq(x,2)), eq(y,3))"))

我有以下形式的输出:

['and', ['or', ['eq', ['x', '1'], 'eq', ['x', '2']], 'eq', ['y', '3']]]

列表输出看起来不错。但是对于后续处理,我希望以嵌套字典的形式输出:

{
    name: 'and',
    args: [
        {
            name: 'or',
            args: [
                {
                    name: 'eq',
                    args: ['x','1']
                },
                {
                    name: 'eq',
                    args: ['x','2']
                }
            ]
        },
        {
            name: 'eq',
            args: ['y','3']
        }
    ]
}

我试过 Dict 类但没有成功。

是否可以在 pyparsing 中实现?或者我应该手动格式化列表输出?

最佳答案

您正在寻找的功能是 pyparsing 中的一个重要功能,即设置结果名称。对于大多数 pyparsing 应用程序,建议使用结果名称。此功能从 0.9 版本开始就有,如

expr.setResultsName("abc")

这允许我访问整个解析结果的这个特定字段作为 res["abc"]res.abc(其中 res 是从 parser.parseString 返回的值)。您还可以调用 res.dump() 来查看结果的嵌套 View 。

但仍然注意让解析器一目了然,我在 1.4.6 中添加了对这种形式的 setResultsName 的支持:

expr("abc")

这是您的解析器,经过一些清理,并添加了结果名称:

COMMA,LPAR,RPAR = map(Suppress,",()")
field = Word(alphanums)
value = Word(alphanums)
eq_ = CaselessLiteral('eq')("name") + Group(LPAR + field + COMMA + value + RPAR)("args")
ne_ = CaselessLiteral('ne')("name") + Group(LPAR + field + COMMA + value + RPAR)("args")
function = ( eq_ | ne_ )

arg = Forward()
and_ = Forward()
or_ = Forward()
exp = Group(and_ | or_ | function)

arg << delimitedList(exp)

and_ << Literal("and")("name") + LPAR + Group(arg)("args") + RPAR
or_ << Literal("or")("name") + LPAR + Group(arg)("args") + RPAR

不幸的是,dump() 只处理结果的嵌套,而不是值列表,所以它不如 json.dumps 好(也许这会是 dump 的一个很好的增强?)。所以这是一个自定义方法来转储嵌套的名称参数结果:

ob = exp.parseString("and(or(eq(x,1), eq(x,2)), eq(y,3))")[0]

INDENT_SPACES = '    '
def dumpExpr(ob, level=0):
    indent = level * INDENT_SPACES
    print (indent + '{')
    print ("%s%s: %r," % (indent+INDENT_SPACES, 'name', ob['name']))
    if ob.name in ('eq','ne'):
        print ("%s%s: %s"   % (indent+INDENT_SPACES, 'args', ob.args.asList()))
    else:
        print ("%s%s: ["   % (indent+INDENT_SPACES, 'args'))
        for arg in ob.args:
            dumpExpr(arg, level+2)
        print ("%s]"   % (indent+INDENT_SPACES))
    print (indent + '}' + (',' if level > 0 else ''))
dumpExpr(ob)

给予:

{
    name: 'and',
    args: [
        {
            name: 'or',
            args: [
                {
                    name: 'eq',
                    args: ['x', '1']
                },
                {
                    name: 'eq',
                    args: ['x', '2']
                },
            ]
        },
        {
            name: 'eq',
            args: ['y', '3']
        },
    ]
}

关于python - pyparsing 的嵌套字典输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238740/

相关文章:

python - 如何使用 Pydantic 将此数据结构转换为 JSON?

Python xml绝对路径

c# - 如何使用 C# 将 XML 解析为 lisp 的 S-Expression?

c - 编写 R 扩展时如何返回命名的 VECSXP

python - 如何在 Django 中测试手动数据库事务代码?

javascript - 无法让 SimpleHTTPRequestHandler 响应 AJAX

python - 你如何用 pyparsing 解析文字星号?

Python/PyParsing : Difficulty with setResultsName

python - 使用 pyparsing 解析 <attribute value> 对时出错