thesis-prediction-ml/building-features-from-text-data/08-PartOfSpeechTagging.ipynb
2023-06-18 14:45:35 +02:00

571 lines
17 KiB
Text

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Part-of-Speech Tagging"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import nltk\n",
"from nltk import word_tokenize"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package tagsets to\n",
"[nltk_data] /Users/loonycorn/nltk_data...\n",
"[nltk_data] Unzipping help/tagsets.zip.\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('tagsets')"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package averaged_perceptron_tagger to\n",
"[nltk_data] /Users/loonycorn/nltk_data...\n",
"[nltk_data] Unzipping taggers/averaged_perceptron_tagger.zip.\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('averaged_perceptron_tagger')"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"$: dollar\n",
" $ -$ --$ A$ C$ HK$ M$ NZ$ S$ U.S.$ US$\n",
"'': closing quotation mark\n",
" ' ''\n",
"(: opening parenthesis\n",
" ( [ {\n",
"): closing parenthesis\n",
" ) ] }\n",
",: comma\n",
" ,\n",
"--: dash\n",
" --\n",
".: sentence terminator\n",
" . ! ?\n",
":: colon or ellipsis\n",
" : ; ...\n",
"CC: conjunction, coordinating\n",
" & 'n and both but either et for less minus neither nor or plus so\n",
" therefore times v. versus vs. whether yet\n",
"CD: numeral, cardinal\n",
" mid-1890 nine-thirty forty-two one-tenth ten million 0.5 one forty-\n",
" seven 1987 twenty '79 zero two 78-degrees eighty-four IX '60s .025\n",
" fifteen 271,124 dozen quintillion DM2,000 ...\n",
"DT: determiner\n",
" all an another any both del each either every half la many much nary\n",
" neither no some such that the them these this those\n",
"EX: existential there\n",
" there\n",
"FW: foreign word\n",
" gemeinschaft hund ich jeux habeas Haementeria Herr K'ang-si vous\n",
" lutihaw alai je jour objets salutaris fille quibusdam pas trop Monte\n",
" terram fiche oui corporis ...\n",
"IN: preposition or conjunction, subordinating\n",
" astride among uppon whether out inside pro despite on by throughout\n",
" below within for towards near behind atop around if like until below\n",
" next into if beside ...\n",
"JJ: adjective or numeral, ordinal\n",
" third ill-mannered pre-war regrettable oiled calamitous first separable\n",
" ectoplasmic battery-powered participatory fourth still-to-be-named\n",
" multilingual multi-disciplinary ...\n",
"JJR: adjective, comparative\n",
" bleaker braver breezier briefer brighter brisker broader bumper busier\n",
" calmer cheaper choosier cleaner clearer closer colder commoner costlier\n",
" cozier creamier crunchier cuter ...\n",
"JJS: adjective, superlative\n",
" calmest cheapest choicest classiest cleanest clearest closest commonest\n",
" corniest costliest crassest creepiest crudest cutest darkest deadliest\n",
" dearest deepest densest dinkiest ...\n",
"LS: list item marker\n",
" A A. B B. C C. D E F First G H I J K One SP-44001 SP-44002 SP-44005\n",
" SP-44007 Second Third Three Two * a b c d first five four one six three\n",
" two\n",
"MD: modal auxiliary\n",
" can cannot could couldn't dare may might must need ought shall should\n",
" shouldn't will would\n",
"NN: noun, common, singular or mass\n",
" common-carrier cabbage knuckle-duster Casino afghan shed thermostat\n",
" investment slide humour falloff slick wind hyena override subhumanity\n",
" machinist ...\n",
"NNP: noun, proper, singular\n",
" Motown Venneboerger Czestochwa Ranzer Conchita Trumplane Christos\n",
" Oceanside Escobar Kreisler Sawyer Cougar Yvette Ervin ODI Darryl CTCA\n",
" Shannon A.K.C. Meltex Liverpool ...\n",
"NNPS: noun, proper, plural\n",
" Americans Americas Amharas Amityvilles Amusements Anarcho-Syndicalists\n",
" Andalusians Andes Andruses Angels Animals Anthony Antilles Antiques\n",
" Apache Apaches Apocrypha ...\n",
"NNS: noun, common, plural\n",
" undergraduates scotches bric-a-brac products bodyguards facets coasts\n",
" divestitures storehouses designs clubs fragrances averages\n",
" subjectivists apprehensions muses factory-jobs ...\n",
"PDT: pre-determiner\n",
" all both half many quite such sure this\n",
"POS: genitive marker\n",
" ' 's\n",
"PRP: pronoun, personal\n",
" hers herself him himself hisself it itself me myself one oneself ours\n",
" ourselves ownself self she thee theirs them themselves they thou thy us\n",
"PRP$: pronoun, possessive\n",
" her his mine my our ours their thy your\n",
"RB: adverb\n",
" occasionally unabatingly maddeningly adventurously professedly\n",
" stirringly prominently technologically magisterially predominately\n",
" swiftly fiscally pitilessly ...\n",
"RBR: adverb, comparative\n",
" further gloomier grander graver greater grimmer harder harsher\n",
" healthier heavier higher however larger later leaner lengthier less-\n",
" perfectly lesser lonelier longer louder lower more ...\n",
"RBS: adverb, superlative\n",
" best biggest bluntest earliest farthest first furthest hardest\n",
" heartiest highest largest least less most nearest second tightest worst\n",
"RP: particle\n",
" aboard about across along apart around aside at away back before behind\n",
" by crop down ever fast for forth from go high i.e. in into just later\n",
" low more off on open out over per pie raising start teeth that through\n",
" under unto up up-pp upon whole with you\n",
"SYM: symbol\n",
" % & ' '' ''. ) ). * + ,. < = > @ A[fj] U.S U.S.S.R * ** ***\n",
"TO: \"to\" as preposition or infinitive marker\n",
" to\n",
"UH: interjection\n",
" Goodbye Goody Gosh Wow Jeepers Jee-sus Hubba Hey Kee-reist Oops amen\n",
" huh howdy uh dammit whammo shucks heck anyways whodunnit honey golly\n",
" man baby diddle hush sonuvabitch ...\n",
"VB: verb, base form\n",
" ask assemble assess assign assume atone attention avoid bake balkanize\n",
" bank begin behold believe bend benefit bevel beware bless boil bomb\n",
" boost brace break bring broil brush build ...\n",
"VBD: verb, past tense\n",
" dipped pleaded swiped regummed soaked tidied convened halted registered\n",
" cushioned exacted snubbed strode aimed adopted belied figgered\n",
" speculated wore appreciated contemplated ...\n",
"VBG: verb, present participle or gerund\n",
" telegraphing stirring focusing angering judging stalling lactating\n",
" hankerin' alleging veering capping approaching traveling besieging\n",
" encrypting interrupting erasing wincing ...\n",
"VBN: verb, past participle\n",
" multihulled dilapidated aerosolized chaired languished panelized used\n",
" experimented flourished imitated reunifed factored condensed sheared\n",
" unsettled primed dubbed desired ...\n",
"VBP: verb, present tense, not 3rd person singular\n",
" predominate wrap resort sue twist spill cure lengthen brush terminate\n",
" appear tend stray glisten obtain comprise detest tease attract\n",
" emphasize mold postpone sever return wag ...\n",
"VBZ: verb, present tense, 3rd person singular\n",
" bases reconstructs marks mixes displeases seals carps weaves snatches\n",
" slumps stretches authorizes smolders pictures emerges stockpiles\n",
" seduces fizzes uses bolsters slaps speaks pleads ...\n",
"WDT: WH-determiner\n",
" that what whatever which whichever\n",
"WP: WH-pronoun\n",
" that what whatever whatsoever which who whom whosoever\n",
"WP$: WH-pronoun, possessive\n",
" whose\n",
"WRB: Wh-adverb\n",
" how however whence whenever where whereby whereever wherein whereof why\n",
"``: opening quotation mark\n",
" ` ``\n"
]
}
],
"source": [
"nltk.help.upenn_tagset()"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('I', 'PRP'),\n",
" ('refuse', 'VBP'),\n",
" ('to', 'TO'),\n",
" ('let', 'VB'),\n",
" ('this', 'DT'),\n",
" ('refuse', 'NN'),\n",
" ('get', 'VB'),\n",
" ('me', 'PRP'),\n",
" ('down', 'RP')]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"I refuse to let this refuse get me down\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('Bear', 'NNP'),\n",
" ('with', 'IN'),\n",
" ('me', 'PRP'),\n",
" (',', ','),\n",
" ('this', 'DT'),\n",
" ('effort', 'NN'),\n",
" ('with', 'IN'),\n",
" ('soon', 'RB'),\n",
" ('bear', 'JJ'),\n",
" ('fruit', 'NN'),\n",
" (',', ','),\n",
" ('otherwise', 'RB'),\n",
" ('we', 'PRP'),\n",
" (\"'ll\", 'MD'),\n",
" ('have', 'VB'),\n",
" ('to', 'TO'),\n",
" ('run', 'VB'),\n",
" ('from', 'IN'),\n",
" ('the', 'DT'),\n",
" ('bear', 'NN')]"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"\"\"Bear with me, this effort with soon bear fruit, \n",
" otherwise we'll have to run from the bear\"\"\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('A', 'DT'),\n",
" ('bird', 'NN'),\n",
" ('in', 'IN'),\n",
" ('hand', 'NN'),\n",
" ('is', 'VBZ'),\n",
" ('worth', 'JJ'),\n",
" ('two', 'CD'),\n",
" ('in', 'IN'),\n",
" ('the', 'DT'),\n",
" ('bush', 'NN'),\n",
" ('.', '.'),\n",
" ('Good', 'JJ'),\n",
" ('things', 'NNS'),\n",
" ('come', 'VBP'),\n",
" ('to', 'TO'),\n",
" ('those', 'DT'),\n",
" ('who', 'WP'),\n",
" ('wait', 'VBP'),\n",
" ('.', '.'),\n",
" ('There', 'EX'),\n",
" ('are', 'VBP'),\n",
" ('other', 'JJ'),\n",
" ('fish', 'NN'),\n",
" ('in', 'IN'),\n",
" ('the', 'DT'),\n",
" ('sea', 'NN'),\n",
" ('.', '.'),\n",
" ('The', 'DT'),\n",
" ('ball', 'NN'),\n",
" ('is', 'VBZ'),\n",
" ('in', 'IN'),\n",
" ('your', 'PRP$'),\n",
" ('court', 'NN'),\n",
" ('.', '.')]"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"text = \"A bird in hand is worth two in the bush. \" +\\\n",
" \"Good things come to those who wait. \" +\\\n",
" \"There are other fish in the sea. \" +\\\n",
" \"The ball is in your court.\"\n",
"\n",
"tokenized_words = word_tokenize(text)\n",
"tagged_words = nltk.pos_tag(tokenized_words)\n",
"tagged_words"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[('NN', 7),\n",
" ('DT', 5),\n",
" ('IN', 4),\n",
" ('.', 4),\n",
" ('JJ', 3),\n",
" ('VBP', 3),\n",
" ('VBZ', 2),\n",
" ('CD', 1),\n",
" ('NNS', 1),\n",
" ('TO', 1)]"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from nltk.probability import FreqDist\n",
"\n",
"fd = FreqDist(tagged_words)\n",
"fd_tagged = FreqDist(tag for (word, tag) in tagged_words)\n",
"fd_tagged.most_common(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Brown Corpus was the first million-word electronic corpus of English, created in 1961 at Brown University. This corpus contains text from 500 sources, and the sources have been categorized by genre, such as news, editorial, and so on. 1.1 gives an example of each genre (for a complete list, see http://icame.uib.no/brown/bcm-los.html)."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"[nltk_data] Downloading package brown to /Users/loonycorn/nltk_data...\n",
"[nltk_data] Package brown is already up-to-date!\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.download('brown')"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['The',\n",
" 'Fulton',\n",
" 'County',\n",
" 'Grand',\n",
" 'Jury',\n",
" 'said',\n",
" 'Friday',\n",
" 'an',\n",
" 'investigation',\n",
" 'of']"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"nltk.corpus.brown.words()[:10]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"text = nltk.Text(word.lower() for word in nltk.corpus.brown.words())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lexical categories like \"noun\" and part-of-speech tags like NN seem to have their uses, but the details will be obscure to many readers. You might wonder what justification there is for introducing this extra level of information. Many of these categories arise from superficial analysis the distribution of words in text. Consider the following analysis involving woman (a noun), bought (a verb), over (a preposition), and the (a determiner). The text.similar() method takes a word w, finds all contexts w1w w2, then finds all words w' that appear in the same context, i.e. w1w'w2."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Similar words here belong to the same part of speech"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"man time day way girl year house people world city family state room\n",
"country car woman program church government job\n"
]
}
],
"source": [
"text.similar('boy')"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"get be do in see work go have take make put and find time look day say\n",
"use come show\n"
]
}
],
"source": [
"text.similar('run')"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"in on to of and for with from at by that into as up out down through\n",
"is all about\n"
]
}
],
"source": [
"text.similar('over')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}