0% found this document useful (0 votes)
2 views

Lab Assignment-10

The document provides Python code examples using the NLTK library to print parts of speech (POS) and parse trees for given text. It includes three separate code snippets that demonstrate how to extract noun phrases, verbs, and prepositional phrases from sentences. Each snippet utilizes the RegexpParser to define grammar patterns for parsing the specified sentence structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab Assignment-10

The document provides Python code examples using the NLTK library to print parts of speech (POS) and parse trees for given text. It includes three separate code snippets that demonstrate how to extract noun phrases, verbs, and prepositional phrases from sentences. Each snippet utilizes the RegexpParser to define grammar patterns for parsing the specified sentence structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

10. Write a program to print POS and parse tree of a given Text.

a.
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
from nltk import pos_tag, word_tokenize, RegexpParser

# Example text
sample_text = "The quick brown fox jumps over the lazy dog"

# Find all parts of speech in above sentence


tagged = pos_tag(word_tokenize(sample_text))

#Extract all parts of speech from any text


chunker = RegexpParser("""
NP: {<DT>?<JJ>*<NN>} #To extract Noun Phrases
P: {<IN>} #To extract Prepositions
V: {<V.*>} #To extract Verbs
PP: {<p> <NP>} #To extract Prepositional Phrases
VP: {<V> <NP|PP>*} #To extract Verb Phrases
""")

# Print all parts of speech in above sentence


output = chunker.parse(tagged)
print("After Extracting\n", output)

b.
import nltk
sentence = [
("a", "DT"),
("clever", "JJ"),
("fox","NN"),
("was","VBP"),
("jumping","VBP"),
("over","IN"),
("the","DT"),
("wall","NN")
]
grammar = "NP:{<DT>?<JJ>*<NN>}"
Reg_parser = nltk.RegexpParser(grammar)
Reg_parser.parse(sentence)
Output = Reg_parser.parse(sentence)
Output.draw()

c.
import nltk
sentence = [("the", "DT"), ("little", "JJ"), ("yellow", "JJ"), ("dog", "NN"),
("barked","VBD"), ("at", "IN"), ("the", "DT"), ("cat", "NN")]

pattern = "NP: {<DT>?<JJ>*<NN>}"


NPChunker = nltk.RegexpParser(pattern)
result = NPChunker.parse(sentence)
result.draw()

You might also like