Question

I'm new to Python and pyparsing, and I'm making a logic expression evaluator.

The formula must be a WFF. The BNF of WFF is:

<alpha set> ::= p | q | r | s | t | u | ... 
(the arbitrary finite set of propositional variables)   

<form> ::= <alpha set> | ¬<form> | (<form>V<form>) | (<form>^<form>) 
           | (<form> -> <form>) | (<form> <-> <form>)

My code is:

'''
Created on 17/02/2012

@author: Juanjo

'''

from pyparsing import *
from string import lowercase

def fbf():
    atom  = Word(lowercase, max=1) #aphabet
    op = oneOf('^ V => <=>') #Operators
    identOp = oneOf('( [ {')
    identCl = oneOf(') ] }')
    form = Forward() #Iniciar de manera recursiva
    #Grammar:
    form << ( (Group(Literal('~') + form)) | ( Group(identOp + form + op + form + identCl) ) | ( Group(identOp + form + identCl) ) | (atom) )

    return form

entrada = raw_input("Input please: ") #userinput
print fbf().parseString(entrada)

The problem is when I use these expressions: a^b and aVb.

The parser should return an error, but there's no error; instead it returns a. Actually, any symbol after a will be ignored.

The WFF version of those forms are: (a^b) and (aVb)

Both work correctly. I think the problem is in the atom definition.

What am I doing wrong?

Was it helpful?

Solution

By default parseString will just parse the beginning of the string.

You can force it to parse the entire string by changing the code to:

print fbf().parseString(entrada, parseAll=True)

Alternatively, you can end the grammar with the StringEnd() token - see the documentation under parseString in http://packages.python.org/pyparsing/ for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top