如何在python上存储和读取我的逻辑操作

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

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

    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]:
hgy1111 回答:如何在python上存储和读取我的逻辑操作

您可以使用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<name>)子表达式内分配的名称来访问过滤器的某些部分

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是您需要解决的问题。

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

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

而不是过于笼统的

r'[^A-Z]+'
本文链接:https://www.f2er.com/3000145.html

大家都在问