我的代码是基于http://pyparsing.wikispaces.com/file/view/simpleBool.py/451074414/simpleBool.py的,我想解析语言生成的单词,如下所示:
ABC:"a“和BCA:"b”或ABC:"d“
解析之后,我想要计算这个表达式的bool值。在代码中,我使用了关键的ABC和BCA,以及dictABC中的ABC:"a“指"a”。
在某个地方我犯了错误,但我找不到哪里,转换成bool总是返回真实。
产出:
调试self.value=True [ABC:“A”真] 调试self.value=False [ABC:“h”假]
代码:
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))发布于 2018-02-13 18:28:19
如果在程序结束时添加:
print(type(res), bool(res))
print(type(res[0]), bool(res[0]))你终究会明白的
<class 'pyparsing.ParseResults'> True
GET V
<class '__main__.BoolOperand'> Falseres不是您解析的操作数,而是解析操作数的ParseResults容器。如果计算res[0],您将看到操作数是如何计算的。
ParseResults在bool方面将具有类似于列表的行为。如果非空,则为True,如果为空,则为False.将这些行添加到程序中:
res.pop(0)
print(bool(res))您将看到ParseResults是False,表示它没有任何内容。
https://stackoverflow.com/questions/48770984
复制相似问题