pyparsing中bool的求值

2024-10-01 05:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码基于http://pyparsing.wikispaces.com/file/view/simpleBool.py/451074414/simpleBool.py 我想分析生成如下单词的语言:

ABC:"a" and BCA:"b" or ABC:"d"

解析之后,我想计算这个表达式的bool值。 在代码中,我有带ABC和BCA键的dict,ABC:“a”表示dict[ABC]中的“a”。你知道吗

在某个地方我犯了错误,但我找不到哪里,转换成布尔总是返回真。你知道吗

输出:

DEBUG self.value=True

[ABC:"a"[True]] True

DEBUG self.value=False

[ABC:"h"[False]] True

代码:

from pyparsing import infixNotation, opAssoc, Keyword, Word, alphas, dblQuotedString, removeQuotes

d = {
    "ABC": "TEST abc TEST",
    "BCA": "TEST abc TEST",
}


class BoolOperand:
    def __init__(self, t):
        self.value = t[2] in d[t[0]]
        print(F"DEBUG self.value={self.value}")
        self.label = f"{t[0]}:\"{t[2]}\"[{str(self.value)}]"

    def __bool__(self):
        print("GET V")
        return self.value

    def __str__(self):
        return self.label

    __nonzero__ = __bool__
    __repr__ = __str__


class BoolBinOp:
    def __init__(self, t):
        self.args = t[0][0::2]

    def __str__(self):
        sep = " %s " % self.reprsymbol
        return "(" + sep.join(map(str, self.args)) + ")"

    def __bool__(self):
        print("DEBUG BoolBinOp")
        return self.evalop(bool(a) for a in self.args)

    __nonzero__ = __bool__
    __repr__ = __str__


class BoolAnd(BoolBinOp):
    reprsymbol = '&'
    evalop = all


class BoolOr(BoolBinOp):
    reprsymbol = '|'
    evalop = any


class BoolNot:
    def __init__(self, t):
        self.arg = t[0][1]

    def __bool__(self):
        print("DEBUG BoolNot")
        v = bool(self.arg)
        return not v

    def __str__(self):
        return "~" + str(self.arg)

    __repr__ = __str__
    __nonzero__ = __bool__


EXPRESSION = Word(alphas) + ":" + dblQuotedString().setParseAction(removeQuotes)
TRUE = Keyword("True")
FALSE = Keyword("False")
boolOperand = TRUE | FALSE  | EXPRESSION
boolOperand.setParseAction(BoolOperand)

boolExpr = infixNotation(boolOperand,
                         [
                             ("not", 1, opAssoc.RIGHT, BoolNot),
                             ("and", 2, opAssoc.LEFT, BoolAnd),
                             ("or", 2, opAssoc.LEFT, BoolOr),
                         ])

if __name__ == "__main__":
    res = boolExpr.parseString('ABC:"a"')
    print(res, "\t", bool(res))
    print("\n\n")
    res = boolExpr.parseString('ABC:"h"')
    print(res, "\t", bool(res))

Tags: debugtestselftruereturnvaluedefres
1条回答
网友
1楼 · 发布于 2024-10-01 05:04:03

如果在课程结束时添加:

print(type(res), bool(res))
print(type(res[0]), bool(res[0]))

你会看到的

<class 'pyparsing.ParseResults'> True
GET V
<class '__main__.BoolOperand'> False

res不是已解析的操作数,它是已解析操作数的ParseResults容器。如果您计算res[0],您将看到操作数是如何计算的。你知道吗

ParseResults将具有与bool相关的列表类似的行为。如果非空,则为True,如果为空,则为False。将这些行添加到程序中:

res.pop(0)
print(bool(res))

您将看到ParseResultsFalse,表示它没有内容。你知道吗

相关问题 更多 >