Uncategorized

Python Lex Yacc : Regular Expression Error


I am trying PLY for sentence validation. I take a simple grammar rule.

Sentence -> nouns verbs
nouns -> r'[A-Za-z]'
verbs -> is|are|am|.. 

When I just set verbs to is|am or am i.e. I keep my choices to detect atmost two types of verbs, PLY throws an error.

My code is

import ply.lex as lex
import ply.yacc as yacc

tokens = ['WORDS','VERBS']

def t_WORDS(t):
    r'[A-Za-z]+'
    pass
    
def t_VERBS(t):
    r'(is|are|am)'
    pass                                                                                                                                                            

t_ignore=" \t\n"

def t_error(t):
    print('Lexical error')
    t.lexer.skip(1)

def p_sentence(p):
    'sentence : WORDS VERBS'
    p[0] = p[1] + p[2]

def p_error(p):
    print("Error")

lexer = lex.lex()
parser = yacc.yacc()

while True:
    sentence = input("Sentence : ")
    result = parser.parse(sentence)
    print(result)

But when I write

import ply.lex as lex
import ply.yacc as yacc

tokens = ['WORDS','VERBS']

def t_WORDS(t):
    r'[A-Za-z]+'
    pass
    
def t_VERBS(t):
    r'(is|are)'
    pass                                                                                                                                                            

t_ignore=" \t\n"

def t_error(t):
    print('Lexical error')
    t.lexer.skip(1)

def p_sentence(p):
    'sentence : WORDS VERBS'
    p[0] = p[1] + p[2]

def p_error(p):
    print("Error")

lexer = lex.lex()
parser = yacc.yacc()

while True:
    sentence = input("Sentence : ")
    result = parser.parse(sentence)
    print(result)

The error occurs. I have taken example ‘This are’ as a sentence. This works fine when is|are|am are defined but not for is|are.

What have I done wrong?



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *