Natural Language Processing Lab 7
Natural Language Processing Lab 7
Lab Assignment
R.BhanuKiran
22BCE9560
L45+L46
1. implement regex parser to the given sentence
The quick brown fox jumps over the lazy dog
NP-> DT ADJ NN
VP-> V NP LPP
P-> IN
V->V
PP->IN NP
CODE
import re
grammar_rules = {
'NP': r'DT ADJ ADJ NN',
'VP': r'V NP',
'P': r'IN',
'V': r'V',
'PP': r'IN NP'
}
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.lower().split()
part_of_speech_tags = {
'the': 'DT',
'quick': 'ADJ',
'brown': 'ADJ',
'fox': 'NN',
'jumps': 'V',
'over': 'IN',
'lazy': 'ADJ',
'dog': 'NN'
}
def analyze_sentence(parsed_words):
"""Analyze sentence structure based on defined grammar rules."""
print("Parsed words: ", parsed_words)
analyze_sentence(parsed_words)
output
sentences = [
"I prefer morning fight through denver",
"The Dog barked loudly at the stranger",
"The quick brown fox jumped over the lazy dog",
"i booked a fight from vijayawada to delhi",
"John saw a dog yesterday which was a yokshire terrier"
]
def shift_word(self):
if self.input_buffer:
word = self.input_buffer.pop(0)
self.stack.append(word)
self.transition_log.append(f"Shift: {word}")
def reduce_stack(self):
if len(self.stack) >= 2:
dependent_word = self.stack.pop()
head_word = self.stack[-1]
arc = (head_word, dependent_word) # head_word ->
dependent_word (dependency arc)
self.dependency_arcs.append(arc)
self.transition_log.append(f"Reduce: {head_word} ->
{dependent_word}")
def parse_sentence(self):
while self.input_buffer:
self.shift_word()
self.display_current_state()
if len(self.stack) > 1:
if self.stack[-1] in ["try", "booked", "flight", "someplace", "new"]:
self.reduce_stack()
self.display_current_state()
while len(self.stack) > 1:
self.reduce_stack()
self.display_current_state()
def display_current_state(self):
print(f"Stack: {self.stack}")
print(f"Input Buffer: {' '.join(self.input_buffer)}")
print(f"Dependency Arcs: {self.dependency_arcs}")
print(f"Transitions Log: {self.transition_log}")
print("-" * 50)
sentence1 = "I wanted to try someplace new"
sentence2 = "I booked a flight from delhi to vijayawada"
print("Parsing sentence 1:")
parser1 = SimpleShiftReduceParser(sentence1)
parser1.parse_sentence()
print("\nParsing sentence 2:")
parser2 = SimpleShiftReduceParser(sentence2)
parser2.parse_sentence()