Pyparsing中的Excel幂运算符

2024-09-27 07:35:35 发布

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

我正在尝试编写一个解析器来解析Excel公式。当我尝试实现power操作符时,抛出了一些错误,但我不确定哪里出了问题?你知道吗

完整代码

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)

如何着手解决这个问题?你知道吗


Tags: groupoptionalwordpowerexpropassocalphasexcl

热门问题