【问题标题】:How to store and read my logical operation on python如何在python上存储和读取我的逻辑操作
【发布时间】:2019-12-01 05:03:43
【问题描述】:

我正在编写一个程序来使用一些参数和逻辑操作来过滤我的数据。

我有很多有其特点的教室数据,所以每个教室都会有不同的过滤器。

    if classrooms == 1:
       if data[A] > data[B] & data[C] != data [D]:
         print("matched")
    elif classrooms == 2:
       if data[A] < data[B] & data[C] == data [D]:
         print("matched")
    elif classrooms == 3:
       if data[B] < data[D] & data[A] == data [C]:
         print("matched")
...
...
    elif classrooms == 5000:
       if data[R] < data[A] & data[W] == data [H]:
         print("matched")

由于运算符相似,有没有什么方法可以将我的逻辑过滤器从我存储的文件中读取到python程序中?

"(A<B)&(C!=D)"
"(A>B)&(C==D)"
..
..
"(R<A)&(W==H)"

因此,我不必在 python 中为每个教室编写所有逻辑过滤器,这会导致 python 中出现大行。我刚刚从我存储的文本数据中读取,我的 python 程序将解释

"(A<B)&(C!=D)"

到这个程序

if data[A] > data[B] & data[C] != data [D]:

【问题讨论】:

    标签: python parsing tokenize logical-operators


    【解决方案1】:

    您可以使用regular expression 解析文件中的过滤器,然后从操作员模块构造函数链来执行过滤器。

    这个表达式

    import re
    rx = re.compile(r"""^                         # Beginning of string
                        \(                        # Opening outer parenthesis
                        (?P<operand0>[A-Z])       # First operand
                        (?P<operator0>[^A-Z]+)    # First operator
                        (?P<operand1>[A-Z])       # Second operand
                        \)                        # Closing outer parenthesis
                        (?P<operator1>[^A-Z]+)    # Second operator
                        \(                        # Opening oute parenthesis
                        (?P<operand2>[A-Z])       # Third operand
                        (?P<operator2>[^A-Z]+)    # Third operator
                        (?P<operand3>[A-Z])       # Fourth operand
                        \)                        # Closing outer parenthesis
                        $                         # End of string
                        """,
                    re.VERBOSE)
    

    与过滤器的结构相匹配。

    它们可以这样匹配:

    m = rx.match("(A<B)&(C!=D)")
    

    可以使用(?P&lt;name&gt;) 子表达式中分配的名称访问过滤器的某些部分

    m['operand0']
    'A'
    m['operator0']
    '<'
    

    使用字典将运算符映射到 operator 模块中的函数

    import operator
    lookup = {
        '<': operator.lt,
        '&': operator.and_,
        '!=': operator.ne,
    }
    

    你可以构建一个表达式并计算它

    op0 = lookup[m['operator0']]
    op1 = lookup[m['operator1']]
    op2 = lookup[m['operator2']]
    
    result = op1(op0(a, b), op2(c, d))
    

    如何从操作数派生a, b, c, d 是您需要解决的问题。

    上面的正则表达式假定操作数是单个大写字符,运算符是一个或多个非大写字符。这可以更精确,例如,您可以使用正则表达式交替运算符 | 来创建一个仅匹配使用的运算符的表达式

    r'&|<|>|!=|=='
    

    而不是过于笼统

    r'[^A-Z]+'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2021-08-09
      • 2019-02-18
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多