O'Reilly logo

Python 2.6 Text Processing Beginner's Guide by Jeff McNeil

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action - implementing a calculator

Given that our BNF example earlier in the chapter allows for simple arithmetic, it only makes sense to extend it and implement a text-based calculator as our first PyParsing example. In this example, we'll do just that. We'll only support four basic operations and will limit our example to two terms.

  1. Create a new file and name it calc.py.
  2. Enter the following Python code:
     import sys import operator from pyparsing import nums, oneOf, Word from pyparsing import ParseException # Map math operations to callable functions within # the operator module. op_map = { '*': operator.mul, '+': operator.add, '/': operator.div, '-': operator.sub } # define grammar MATH_GRAMMAR = Word(nums).setResultsName('first_term') ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required