python - 从python中的字符串解析嵌套逻辑

标签 python sqlalchemy pyparsing

我需要转换一个形式的字符串:

'a==1&&(b==2||(c==3||d==4&&e==5)&&f==6)||(g==7&&h==8)'

进入要过滤的 sqlalchemy 逻辑(通过 or_and_)。第一步实际上是将字符串解析为有用的东西。我想把它写成以下形式:

['a==1','&&',['b==2','||',['c==3','||','d==4','&&','e==5'],'&&','f==6'],'||',['g==7','&&','h==8']]

然后递归地逐步解析它。不幸的是,我在这个解析步骤中遇到了麻烦,因为我以前从未使用过 pyparsing。

编辑(解决方案)

我无法在 so 或 interblag 上找到直接的解决方案,但在对文档进行大量挖掘之后,我设法将以下简单表达式放在一起:

from pyparsing import Word, alphanums, nestedExpr

content  = Word( alphanums + '=' ) | '||' | '&&'
unnester = nestedExpr( content = content )

a = 'a==3||b==1&&(c==4||(d==1||e==5)&&f==9)'
unnester.parseString( '(' + a + ')' ).asList()

只要在迭代过程中执行展平步骤,这似乎工作得很好。

最佳答案

我也没有真正使用过 pyparsing,但这里有一个直接的 python 实现,可以做你想做的事:

import re
from collections import namedtuple

TOKENIZER = re.compile(r"\w+==\w+|&&|\|\||[()]").findall

Node = namedtuple("Node", ["parent", "children"])

def syntax_tree(text, tokenizer, brackets):
    root = cur_node = Node(None, [])
    stack = []
    for token in tokenizer(text):
        if token == brackets["("]:
            stack.append(token)
            new_node = Node(cur_node, [])
            cur_node.children.append(new_node)
            cur_node = new_node
        elif token == brackets[")"]:
            if stack and stack.pop() == brackets[")"]:
                cur_node = cur_node.parent
            else:
                raise Exception("Parse error: unmatched parentheses")
        else:
            cur_node.children.append(token)

        if stack:
            raise Exception("Parse error: unmatched parentheses")

    return root

def listify(root):
    if isinstance(root, Node):
        return [listify(item) for item in root.children]
    else:
        return root


if __name__ == "__main__":
    expr = "a==1&&(b==2||(c==3||d==4&&e==5)&&f==6)||(g==7&&h==8)"

    tree = syntax_tree(expr, TOKENIZER, {"(": "(", ")": ")"})
    obj = listify(tree)

关于python - 从python中的字符串解析嵌套逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16187507/

相关文章:

python - 是否有任何 python 模块可以获取文本并向其添加 python 语法突出显示?

python - 在 virtualenv 中安装 PyQt4

python - 如何在 .txt 文件中的 JSON 对象之间添加逗号,然后在 Python 中将其转换为 JSON 数组

python - backref lazy ='dynamic' - 不支持对象填充 - 无法应用预加载

python - SQLAlchemy - 关系不仅限于外键

python - 使用 Pyparsing 为上下文相关元素编写语法规则

python - "tf.train.replica_device_setter"是如何工作的?

python - SQLAlchemy 确定唯一约束是否存在

python - 使用 pyparsing 进行非贪婪列表解析

c++ - 如何在 WIndows 上使用 Cython 编译 Pyparsing?