Parts of Speech (POS)

Parts of Speech is identifying what each other resemble in the particular sentence, with nltk we can get the parts of speech tags returned from a particular sentence, from which we will able to retrieve particular type of words (lets say only nouns) and get the information about the document(which contains multiple sentences), here we will see how we can get information of "moby dick" book by finding only nouns, then do the frequencey distribution, then finding the most common words of distribution.


In [1]:
# Get the nltk
import nltk

In [2]:
# the original text
text = "I walked to the cafe to buy coffee after work."

In [3]:
# Tokenizing the sentences into words
tokens = nltk.word_tokenize(text)

In [4]:
# Calling the .pos_tag() to get the POS tags of the tokens
nltk.pos_tag(tokens)


Out[4]:
[('I', 'PRP'),
 ('walked', 'VBD'),
 ('to', 'TO'),
 ('the', 'DT'),
 ('cafe', 'NN'),
 ('to', 'TO'),
 ('buy', 'VB'),
 ('coffee', 'NN'),
 ('after', 'IN'),
 ('work', 'NN'),
 ('.', '.')]

In [5]:
# For understanding the abbrevations of POS short cuts given above try below command
nltk.help.upenn_tagset()


$: dollar
    $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$
'': closing quotation mark
    ' ''
(: opening parenthesis
    ( [ {
): closing parenthesis
    ) ] }
,: comma
    ,
--: dash
    --
.: sentence terminator
    . ! ?
:: colon or ellipsis
    : ; ...
CC: conjunction, coordinating
    & 'n and both but either et for less minus neither nor or plus so
    therefore times v. versus vs. whether yet
CD: numeral, cardinal
    mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-
    seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025
    fifteen 271,124 dozen quintillion DM2,000 ...
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
EX: existential there
    there
FW: foreign word
    gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous
    lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte
    terram fiche oui corporis ...
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 ...
JJ: adjective or numeral, ordinal
    third ill-mannered pre-war regrettable oiled calamitous first separable
    ectoplasmic battery-powered participatory fourth still-to-be-named
    multilingual multi-disciplinary ...
JJR: adjective, comparative
    bleaker braver breezier briefer brighter brisker broader bumper busier
    calmer cheaper choosier cleaner clearer closer colder commoner costlier
    cozier creamier crunchier cuter ...
JJS: adjective, superlative
    calmest cheapest choicest classiest cleanest clearest closest commonest
    corniest costliest crassest creepiest crudest cutest darkest deadliest
    dearest deepest densest dinkiest ...
LS: list item marker
    A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005
    SP-44007 Second Third Three Two * a b c d first five four one six three
    two
MD: modal auxiliary
    can cannot could couldn't dare may might must need ought shall should
    shouldn't will would
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 ...
NNP: noun, proper, singular
    Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos
    Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA
    Shannon A.K.C. Meltex Liverpool ...
NNPS: noun, proper, plural
    Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists
    Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques
    Apache Apaches Apocrypha ...
NNS: noun, common, plural
    undergraduates scotches bric-a-brac products bodyguards facets coasts
    divestitures storehouses designs clubs fragrances averages
    subjectivists apprehensions muses factory-jobs ...
PDT: pre-determiner
    all both half many quite such sure this
POS: genitive marker
    ' 's
PRP: pronoun, personal
    hers herself him himself hisself it itself me myself one oneself ours
    ourselves ownself self she thee theirs them themselves they thou thy us
PRP$: pronoun, possessive
    her his mine my our ours their thy your
RB: adverb
    occasionally unabatingly maddeningly adventurously professedly
    stirringly prominently technologically magisterially predominately
    swiftly fiscally pitilessly ...
RBR: adverb, comparative
    further gloomier grander graver greater grimmer harder harsher
    healthier heavier higher however larger later leaner lengthier less-
    perfectly lesser lonelier longer louder lower more ...
RBS: adverb, superlative
    best biggest bluntest earliest farthest first furthest hardest
    heartiest highest largest least less most nearest second tightest worst
RP: particle
    aboard about across along apart around aside at away back before behind
    by crop down ever fast for forth from go high i.e. in into just later
    low more off on open out over per pie raising start teeth that through
    under unto up up-pp upon whole with you
SYM: symbol
    % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***
TO: "to" as preposition or infinitive marker
    to
UH: interjection
    Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen
    huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly
    man baby diddle hush sonuvabitch ...
VB: verb, base form
    ask assemble assess assign assume atone attention avoid bake balkanize
    bank begin behold believe bend benefit bevel beware bless boil bomb
    boost brace break bring broil brush build ...
VBD: verb, past tense
    dipped pleaded swiped regummed soaked tidied convened halted registered
    cushioned exacted snubbed strode aimed adopted belied figgered
    speculated wore appreciated contemplated ...
VBG: verb, present participle or gerund
    telegraphing stirring focusing angering judging stalling lactating
    hankerin' alleging veering capping approaching traveling besieging
    encrypting interrupting erasing wincing ...
VBN: verb, past participle
    multihulled dilapidated aerosolized chaired languished panelized used
    experimented flourished imitated reunifed factored condensed sheared
    unsettled primed dubbed desired ...
VBP: verb, present tense, not 3rd person singular
    predominate wrap resort sue twist spill cure lengthen brush terminate
    appear tend stray glisten obtain comprise detest tease attract
    emphasize mold postpone sever return wag ...
VBZ: verb, present tense, 3rd person singular
    bases reconstructs marks mixes displeases seals carps weaves snatches
    slumps stretches authorizes smolders pictures emerges stockpiles
    seduces fizzes uses bolsters slaps speaks pleads ...
WDT: WH-determiner
    that what whatever which whichever
WP: WH-pronoun
    that what whatever whatsoever which who whom whosoever
WP$: WH-pronoun, possessive
    whose
WRB: Wh-adverb
    how however whence whenever where whereby whereever wherein whereof why
``: opening quotation mark
    ` ``

In [6]:
# Now let us try to see how a word is tagged differently on different contexts of two different sentences
# Observe the 'desert' word
# Sentence 1
nltk.pos_tag(nltk.word_tokenize('I will have a desert'))


Out[6]:
[('I', 'PRP'), ('will', 'MD'), ('have', 'VB'), ('a', 'DT'), ('desert', 'NN')]

In [7]:
# Sentence 2
nltk.pos_tag(nltk.word_tokenize('They will desert us.'))


Out[7]:
[('They', 'PRP'), ('will', 'MD'), ('desert', 'VB'), ('us', 'PRP'), ('.', '.')]

In [8]:
# From the above two sentences it is clear 
# that in first sentence 'desert' is used to tell about course of meal - so marked as NN - noun
# in second sentence 'desert' is used to say someone left someone - so marked as VB - verb

In [9]:
# Now lets work on the 'Moby Dick' book and use POS to get the information about the book
# Getting the moby dick book - words
md = nltk.corpus.gutenberg.words('melville-moby_dick.txt')

In [10]:
# Normalize it - checking all words with only alphabets, converting all words to lower case
md_norm = [word.lower() for word in md if word.isalpha()]

In [11]:
# Rather than giving with the short cuts lets try to get the unviersal abbrevations like NOUN, VERB etc
md_tags = nltk.pos_tag(md_norm, tagset='universal')

In [12]:
# Printing the first five tags, see that tags are now in universal form
md_tags[:5]


Out[12]:
[('moby', 'NOUN'),
 ('dick', 'NOUN'),
 ('by', 'ADP'),
 ('herman', 'NOUN'),
 ('melville', 'NOUN')]

In [13]:
# Now get only the noun tag labelled values from tuples ('value', 'Universal form') -> 'value' if 'Universal form' == 'NOUN'
md_nouns = [word[0] for word in md_tags if word[1] == 'NOUN']

In [14]:
# Printing the first 10 nouns we identified
md_nouns[:10]


Out[14]:
['moby',
 'dick',
 'herman',
 'melville',
 'etymology',
 'consumptive',
 'usher',
 'grammar',
 'school',
 'pale']

In [15]:
# Now using frequency distribution and most common words to get the most used words
md_nouns_fd = nltk.FreqDist(md_nouns)
# Getting the first 10 most common
md_nouns_fd.most_common(10)
# We can see that words like 'whale', 'man', 'sea' etc - it talks more about the sailing of man on Sea ??


Out[15]:
[('i', 1182),
 ('whale', 909),
 ('s', 774),
 ('man', 527),
 ('ship', 498),
 ('sea', 435),
 ('head', 337),
 ('time', 334),
 ('boat', 332),
 ('ahab', 278)]

In [ ]: