NLTK tell if word is generated by CFG

58 views Asked by At

Given string and a context-free grammar I need to tell if the grammar generates the string or not using NLTK

I tried using some opensource solution from github but it doesnt work correctly with this example:

S ->
S -> B A10 | B0
A1 -> T A2
A10 -> T A20 | T0
A2 -> c
A20 -> c |
T -> b
T0 -> b |
T -> C T
T0 -> C T0 | C0
B -> a
B0 -> a
B0 ->
S0 -> B A1
C -> b
C0 -> b |

and string a b b b c, which is in the CFL but the solution says its not

1

There are 1 answers

1
rideau On

You can just use RecursiveDescentParser from https://www.nltk.org/howto/parse.html and iterate over parser.parse(word), if you iterate more than 0 times - word is in the language.