【问题标题】:Boolean expression as String - Parsing in Python布尔表达式作为字符串 - 在 Python 中解析
【发布时间】:2021-07-11 15:10:54
【问题描述】:

我想用python编写一个解析器程序,它解析给定的字符串并将其存储在树数据结构中。

示例输入:“(1 OR (2 AND 3) OR 4)”

预期输出:

有人可以指导我吗?

【问题讨论】:

  • 你有字符串还是需要制作
  • 我有一个字符串。我需要解析这个字符串来实现我在问题中提到的任务。
  • 我觉得这个表达不太好,你怎么知道,2,3是和Function1挂钩的
  • 我有单独的函数来计算给定值列表的合取和析取。在我给出的字符串中,2,3 在它们之间有一个运算符 AND。所以我想解析和检测操作数 2,3 与运算符 AND 连接。接下来我想把 2,3 放到一个单独的列表中,并将这个列表传递给计算合取的“function1”。
  • 我的表情会喜欢'FUNC1(OR(1,FUNC2(AND(2,3)),4))',如果可以的话,我会指路

标签: python string-parsing boolean-expression


【解决方案1】:

对于更复杂的字符串解析,你应该考虑使用正则表达式,Python中有一个名为re的库提供了它:

import re

pattern = '[0-9]'
nums = re.findall(pattern, '(1 OR (2 AND 3) OR 4)')

print(nums)
>>> ['1', '2', '3', '4']

https://docs.python.org/3/library/re.html

【讨论】:

    【解决方案2】:

    eval是单词,你要找的,最简单的方法是

    def FUNC1(f1):
        ''' do you logic'''
        print('In FUNC1 --',locals())
        print('returning 10')
        return 10 #dummy
    
          
    def FUNC2(f2):
        ''' do you logic'''
    
        print('In FUNC2 --',locals())
        print('returning 20')
        return 20 #dummy
    
          
    def AND(*args):
        ''' do you logic'''
    
        print('In AND --',locals())
        print('returning 30')
        return 30 #dummy
    
    
    def OR(*args):
        ''' do you logic'''
    
        print('In OR --',locals(),)
        print('returning 40')
        return 40 #dummy
    
    expression = 'FUNC1(OR(1,FUNC2(AND(2,3)),4))'
    
    ## evaluate expression
    eval(expression)
    
    ##output      
    ##In AND -- {'args': (2, 3)}
    ##returning 30
    ##In FUNC2 -- {'f2': 30}
    ##returning 20
    ##In OR -- {'args': (1, 20, 4)}
    ##returning 40
    ##In FUNC1 -- {'f1': 40}
    ##returning 10
    

    另一种方式是https://docs.python.org/3/library/ast.html

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2019-02-10
      • 1970-01-01
      相关资源
      最近更新 更多