Articles → NLP → Context-Free Grammar In NLP

Context-Free Grammar In NLP






What Is Context-Free Grammar?







Formula




Picture showing the formula for context-free grammar


ComponentDescription
VThis is a variable or placeholder. They represent categories like Sentence (S), Noun Phrase (NP), Verb Phrase (VP), etc.hey are replaced step by step until only actual words are left.
ΣThese are actual words.
RGrammar rules
SStart Symbol



Derivation Sequence






S
→ NP VP
→ Det N VP
→ the boy VP
→ the boy V NP
→ the boy plays NP
→ the boy plays PP
→ the boy plays P NP
→ the boy plays with NP
→ the boy plays with Det N
→ the boy plays with a ball



Code


import nltk
from nltk import CFG

# 1. Define the CFG grammar
# The fix: added 'V PP' to the VP rule to allow for a verb followed by a prepositional phrase
grammar = CFG.fromstring("""
S -> NP VP
NP -> Det N | Det N PP | N
VP -> V NP | VP PP | V PP
PP -> P NP

Det -> 'the' | 'a'
N -> 'boy' | 'ball'
V -> 'plays'
P -> 'with'
""")

# 2. Input sentence (must match grammar exactly!)
sentence = ['the', 'boy', 'plays', 'with', 'a', 'ball']

# 3. Create the parser
parser = nltk.ChartParser(grammar)

# 4. Try parsing and show derivation
found = False
for tree in parser.parse(sentence):
    found = True
    print("Parse tree found!\n")
    print(tree)  # Bracketed form
    tree.pretty_print()  # Nice aligned print
    print("\nProductions (Derivation sequence):")
    for prod in tree.productions():
        print(prod)

if not found:
    print("No valid parse found. Check grammar or sentence.")





Posted By  -  Karan Gupta
 
Posted On  -  Monday, September 8, 2025

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250