tagging is an essential feature of text processing where we tag the words into grammatical categorization. we take help of tokenization and pos_tag function to create the tags for each word.
import nltk
text = nltk.word_tokenize("a python is a serpent which eats eggs from the nest")
tagged_text=nltk.pos_tag(text)
print(tagged_text)
when we run the above program, we get the following output −
[('a', 'dt'), ('python', 'nnp'), ('is', 'vbz'), ('a', 'dt'), ('serpent', 'nn'),
('which', 'wdt'), ('eats', 'vbz'), ('eggs', 'nns'), ('from', 'in'),
('the', 'dt'), ('nest', 'jjs')]
tag descriptions
we can describe the meaning of each tag by using the following program which shows the in-built values.
import nltk
nltk.help.upenn_tagset('nn')
nltk.help.upenn_tagset('in')
nltk.help.upenn_tagset('dt')
when we run the above program, we get the following output −
nn: noun, common, singular or mass
common-carrier cabbage knuckle-duster casino afghan shed thermostat
investment slide humour falloff slick wind hyena override subhumanity
machinist ...
in: preposition or conjunction, subordinating
astride among uppon whether out inside pro despite on by throughout
below within for towards near behind atop around if like until below
next into if beside ...
dt: determiner
all an another any both del each either every half la many much nary
neither no some such that the them these this those
tagging a corpus
we can also tag a corpus data and see the tagged result for each word in that corpus.
import nltk
from nltk.tokenize import sent_tokenize
from nltk.corpus import gutenberg
sample = gutenberg.raw("blake-poems.txt")
tokenized = sent_tokenize(sample)
for i in tokenized[:2]:
words = nltk.word_tokenize(i)
tagged = nltk.pos_tag(words)
print(tagged)
when we run the above program we get the following output −
[([', 'jj'), (poems', 'nnp'), (by', 'in'), (william', 'nnp'), (blake', 'nnp'), (1789', 'cd'), (]', 'nnp'), (songs', 'nnp'), (of', 'nnp'), (innocence', 'nnp'), (and', 'nnp'), (of', 'nnp'), (experience', 'nnp'), (and', 'cc'), (the', 'nnp'), (book', 'nnp'), (of', 'in'), (thel', 'nnp'), (songs', 'nnp'), (of', 'nnp'), (innocence', 'nnp'), (introduction', 'nnp'), (piping', 'vbg'), (down', 'rp'), (the', 'dt'), (valleys', 'nn'), (wild', 'jj'), (,', ','), (piping', 'nnp'), (songs', 'nns'), (of', 'in'), (pleasant', 'jj'), (glee', 'nn'), (,', ','), (on', 'in'), (a', 'dt'), (cloud', 'nn'), (i', 'prp'), (saw', 'vbd'), (a', 'dt'), (child', 'nn'), (,', ','), (and', 'cc'), (he', 'prp'), (laughing', 'vbg'), (said', 'vbd'), (to', 'to'), (me', 'prp'), (:', ':'), (``', '``'), (pipe', 'vb'), (a', 'dt'), (song', 'nn'), (about', 'in'), (a', 'dt'), (lamb', 'nn'), (!', '.'), (u"''", "''")]