V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
al0ne
V2EX  ›  Python

Python 如何解析逻辑表达式?

  •  
  •   al0ne ·
    cnnetarmy · 2021-03-27 23:20:23 +08:00 · 2415 次点击
    这是一个创建于 1124 天前的主题,其中的信息可能已经有所发展或是发生改变。
    例如我输入一个条件 status:200 && port:333 这种逻辑表达式,有没有现成的库可以调用?
    7 条回复    2021-03-29 10:17:46 +08:00
    zhuangzhuang1988
        1
    zhuangzhuang1988  
       2021-03-27 23:32:19 +08:00
    antlr
    agagega
        2
    agagega  
       2021-03-27 23:37:37 +08:00 via iPhone
    看你的规则,简单的话套几层 split 就行,也就相当于递归下降了
    ch2
        3
    ch2  
       2021-03-28 00:17:53 +08:00
    如果你想解析任何逻辑表达式,推荐用 yacc
    逻辑简单代码就少,复杂的也不怕
    唯一麻烦的是你得学一下 yacc 语义子程序怎么编写
    ch2
        4
    ch2  
       2021-03-28 00:22:25 +08:00
    比如你这个表达式的形式,可以用四条产生式来概括:
    键->几个字母组成的单词,对应语义子程序是把词法分析捕获的单词 token 归约为一个变量
    值->几个数字组成的数值,对应语义子程序是把词法分析捕获的数字 token 归约为一个变量
    键值对->键:值,对应语义子程序是把当前栈的两个变量合并为一个键值对
    表达式->键值对&&键值对,对应语义子程序是把当前栈的两个键值对合并为一个字典
    matrix67
        5
    matrix67  
       2021-03-28 09:22:50 +08:00
    YACC/Bison generate table driven parsers, which means the "processing logic" is contained in the parser program's data, not so much in the parser's code. The pay off is that even a parser for a very complex language has a relatively small code footprint.

    ANTLR generates recursive descent parsers, which means the "processing logic" is contained in the parser's code, as each production rule of the grammar is represented by a function in the parser's code. The pay off is that it is easier to understand what the parser is doing by reading its code. Also, recursive descent parsers are typically faster than table driven ones.
    kkbblzq
        6
    kkbblzq  
       2021-03-29 09:13:48 +08:00
    如果不怕安全性问题可以直接 eval
    al0ne
        7
    al0ne  
    OP
       2021-03-29 10:17:46 +08:00
    @zhuangzhuang1988
    @agagega
    @ch2
    @kkbblzq
    @matrix67

    谢谢几位大佬 我去试试你们说的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1220 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:17 · PVG 07:17 · LAX 16:17 · JFK 19:17
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.