Skip to content Skip to sidebar Skip to footer

Generating Grammar Rules For Nltk Parse Trees

If I have the sentence 'Mary saw a dog' and the following: pos_tags = ['NNP', 'VBD', 'DT', 'NN'] Is it possible to generate the grammar rules for this sentence so that a parse tre

Solution 1:

You can try:

import nltk
# Define the cfg grammar.
grammar = nltk.parse_cfg("""
S -> NP VP
NP -> 'DT' 'NN'
VP -> 'VB'
VP -> 'VB' 'NN'
""")


# Make your POS sentence into a list of tokens.
sentence = "DT NN VB NN".split(" ")

# Load the grammar into the ChartParser.
cp = nltk.ChartParser(grammar)

# Generate and print the nbest_parse from the grammar given the sentence tokens.for tree in cp.nbest_parse(sentence):
    print tree

But as @alexis highlighted, what you're asking for it rather impossible =)

Post a Comment for "Generating Grammar Rules For Nltk Parse Trees"