我正在尝试编写一个解析器来解析Excel公式。当我试图实现幂运算符时,会抛出一些错误,但我不确定哪里出错了?
完整代码
from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
alphanums, nums, Optional, Group, oneOf, Forward, Regex,
operatorPrecedence, opAssoc, dblQuotedString, delimitedList,
Combine, Literal, QuotedString)
EQ, EXCL, LPAR, RPAR, COLON, COMMA = map(Suppress, '=!():,')
EXCL, DOLLAR, POWER = map(Literal, "!$^")
sheetRef = Word(alphas, alphanums) | QuotedString("'", escQuote="''")
colRef = Optional(DOLLAR) + Word(alphas, max=2)
rowRef = Optional(DOLLAR) + Word(nums)
cellRef = Combine(Group(Optional(sheetRef + EXCL)("sheet") + colRef("col") + rowRef("row")))
cellRange = (Group(cellRef("start") + COLON + cellRef("end"))("range")
| cellRef | Word(alphas, alphanums))
power = Group(cellRef('start') + POWER + cellRef('end'))
print(power)
expr = Forward()
COMPARISON_OP = oneOf("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
ifFunc = (CaselessKeyword("if") +
LPAR +
Group(condExpr)("condition") +
COMMA + expr("if_true") +
COMMA + expr("if_false") + RPAR)
statFunc = lambda name: CaselessKeyword(name) + LPAR + delimitedList(expr) + RPAR
sumFunc = statFunc("sum")
minFunc = statFunc("min")
maxFunc = statFunc("max")
aveFunc = statFunc("ave")
funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc
multOp = oneOf("* /")
addOp = oneOf("+ -")
numericLiteral = Regex(r"\-?\d+(\.\d+)?")
operand = numericLiteral | funcCall | cellRange | cellRef | power
arithExpr = operatorPrecedence(operand,
[
(power, 1, opAssoc.RIGHT),
(multOp, 2, opAssoc.LEFT),
(addOp, 2, opAssoc.LEFT),
])
textOperand = dblQuotedString | cellRef
textExpr = operatorPrecedence(textOperand,
[
('&', 2, opAssoc.LEFT),
])
expr << (arithExpr | textExpr)
test = [
# '=SUM(A1:A5,10,A3+A2)',
'=A1^A3',
]
for i in test:
print((EQ + expr).parseString(i, parseAll=True).asList())
我得到的追溯并不提供信息
pyparsing.ParseException: Expected end of text (at char 2), (line:1, col:3)
如何解决这个问题?