-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathp4_TDnBU_ parsing.py
29 lines (27 loc) · 943 Bytes
/
p4_TDnBU_ parsing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import nltk
from IPython.display import display
# from nltk.parse.chart import TopDownChartParser, BottomUpChartParser
grammar = nltk.CFG.fromstring("""
S -> NP VP
VP -> V NP | V NP PP
PP -> P NP
V -> "saw" | "ate" | "walked"
NP -> "Janice" | "Bob" | Det N | Det N PP
Det -> "a" | "an" | "the" | "my"|"his"
N -> "dog" | "cat" | "telescope" | "park"| "Moon"| "terrace"
P -> "in" | "on" | "by" | "with"| "from"
""")
def parse_sentence(sentence):
tokens = sentence.split()
print("Top Down parsing results: ")
rd_parser = nltk.TopDownChartParser(grammar)
for tree in rd_parser.parse(tokens):
tree.pretty_print()
tree.draw()
print("Bottom Up parsing results: ")
sr_parser = nltk.BottomUpChartParser(grammar)
for tree in sr_parser.parse(tokens):
tree.pretty_print()
tree.draw()
user_input = input("Enter a sentence to parse: ")
parse_sentence(user_input)