import nltk
grammar = nltk.data.load('file:sample_grammar.cfg')
sentence = "John left"
tokens = sentence.split()
rd_parser = nltk.RecursiveDescentParser(grammar, trace=2)
trees = rd_parser.parse(tokens)
sentence = "John left"
tokens = sentence.split()
sr_parser = nltk.ShiftReduceParser(grammar, trace=2)
trees = sr_parser.parse(tokens)
Observe the behaviour of the parser by giving the command:
Exercise 1: Extend the grammar so to recognize as grammatical the sentences below, and check their grammaticality using the top-down parsers.
Check whether your grammar overgenerates by giving an example of ungrammatical sentence that it recognizes as grammatical.
Solution: grammar exercise 1
Exercise 2 Extend the grammar so that it can recognize the following sentences.
Check if the top-down parser terminates. If not, try to think of which is the problem.
Check the bottom-up parser if it does not recognize some of the sentences as grammatical, try to think of which is the reason of its failure.
Solution: Grammar exercise 2
Exercise 3: Extend the grammar so to recognize as grammatical the following phrases as NP.
Exercise 4: Write a CFG for your native language and use either the top-down or the bottom-up parser to check the grammatility of some sentences.