4
# Example of defining an arithmetic expression parser using
5
# the operatorPrecedence helper method in pyparsing.
7
# Copyright 2006, by Paul McGuire
10
from pyparsing import *
12
integer = Word(nums).setParseAction(lambda t:int(t[0]))
13
variable = Word(alphas,exact=1)
14
operand = integer | variable
22
# To use the operatorPrecedence helper:
23
# 1. Define the "atom" operand term of the grammar.
24
# For this simple grammar, the smallest operand is either
25
# and integer or a variable. This will be the first argument
26
# to the operatorPrecedence method.
27
# 2. Define a list of tuples for each level of operator
28
# precendence. Each tuple is of the form
29
# (opExpr, numTerms, rightLeftAssoc, parseAction), where
30
# - opExpr is the pyparsing expression for the operator;
31
# may also be a string, which will be converted to a Literal
32
# - numTerms is the number of terms for this operator (must
34
# - rightLeftAssoc is the indicator whether the operator is
35
# right or left associative, using the pyparsing-defined
36
# constants opAssoc.RIGHT and opAssoc.LEFT.
37
# - parseAction is the parse action to be associated with
38
# expressions matching this operator expression (the
39
# parse action tuple member may be omitted)
40
# 3. Call operatorPrecedence passing the operand expression and
41
# the operator precedence list, and save the returned value
42
# as the generated pyparsing expression. You can then use
43
# this expression to parse input strings, or incorporate it
44
# into a larger, more complex grammar.
46
expr = operatorPrecedence( operand,
47
[("!", 1, opAssoc.LEFT),
48
("^", 2, opAssoc.RIGHT),
49
(signop, 1, opAssoc.RIGHT),
50
(multop, 2, opAssoc.LEFT),
51
(plusop, 2, opAssoc.LEFT),]
65
print expr.parseString(t)