text stringlengths 0 3.35k |
|---|
Natural Language Processing with Python |
Natural Language Processing with Python Steven Bird, Ewan Klein, and Edward Loper Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo |
Natural Language Processing with Python by Steven Bird, Ewan Klein, and Edward Loper Copyright © 2009 Steven Bird, Ewan Klein, and Edward Loper. All rights reserved. Printed in the United States of America. Published by O'Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O'Reilly books may be pu... |
Table of Contents Preface..................................................................... ix 1. Language Processing and Python.......................................... 1 1. 1 Computing with Language: Texts and Words 1 1. 2 A Closer Look at Python: Texts as Lists of Words 10 1. 3 Computing with Language: Simple St... |
3. 10 Summary 121 3. 11 Further Reading 122 3. 12 Exercises 123 4. Writing Structured Programs........................................... 129 4. 1 Back to the Basics 130 4. 2 Sequences 133 4. 3 Questions of Style 138 4. 4 Functions: The Foundation of Structured Programming 142 4. 5 Doing More with Functions 149 4. 6 Pr... |
7. 2 Chunking 264 7. 3 Developing and Evaluating Chunkers 270 7. 4 Recursion in Linguistic Structure 277 7. 5 Named Entity Recognition 281 7. 6 Relation Extraction 284 7. 7 Summary 285 7. 8 Further Reading 286 7. 9 Exercises 286 8. Analyzing Sentence Structure........................................... 291 8. 1 Some Gr... |
11. 5 Working with Toolbox Data 431 11. 6 Describing Language Resources Using OLAC Metadata 435 11. 7 Summary 437 11. 8 Further Reading 437 11. 9 Exercises 438 Afterword: The Language Challenge........................................... 441 Bibliography............................................................... 449... |
Preface This is a book about Natural Language Processing. By “natural language” we mean a language that is used for everyday communication by humans; languages such as Eng-lish, Hindi, or Portuguese. In contrast to artificial languages such as programming lan-guages and mathematical notations, natural languages have ev... |
Audience NLP is important for scientific, economic, social, and cultural reasons. NLP is experi-encing rapid growth as its theories and methods are deployed in a variety of new lan-guage technologies. For this reason it is important for a wide range of people to have a working knowledge of NLP. Within industry, this in... |
Note that this book is not a reference work. Its coverage of Python and NLP is selective, and presented in a tutorial style. For reference material, please consult the substantial quantity of searchable resources available at http://python. org/ and http://www. nltk. org/. This book is not an advanced computer science ... |
ways to parse a sentence, recognize its syntactic structure, and construct representa-tions of meaning (Chapters 8-10). The final chapter is devoted to linguistic data and how it can be managed effectively ( Chapter 11 ). The book concludes with an After-word, briefly discussing the past and future of the field. Within... |
we can use to break a line into its words. To apply a method to an object, we write the object name, followed by a period, followed by the method name, i. e., line. split(). Third, methods have arguments expressed inside parentheses. For instance, in the ex-ample, word. endswith('ing') had the argument 'ing' to indicat... |
NLTK-Data This contains the linguistic corpora that are analyzed and processed in the book. Num Py (recommended) This is a scientific computing library with support for multidimensional arrays and linear algebra, required for certain probability, tagging, clustering, and classifica-tion tasks. Matplotlib (recommended) ... |
Language processing task NLTK modules Functionality Linguistic fieldwork nltk. toolbox Manipulate data in SIL Toolbox format NLTK was designed with four primary goals in mind: Simplicity To provide an intuitive framework along with substantial building blocks, giving users a practical knowledge of NLP without getting b... |
A significant fraction of any NLP syllabus deals with algorithms and data structures. On their own these can be rather dry, but NLTK brings them to life with the help of interactive graphical user interfaces that make it possible to view algorithms step-by-step. Most NLTK components include a demonstration that perform... |
Chapter Arts and Humanities Science and Engineering Chapter 5, Categorizing and Tagging Words 2-4 2-4 Chapter 6, Learning to Classify Text 0-2 2-4 Chapter 7, Extracting Information from Text 2 2-4 Chapter 8, Analyzing Sentence Structure 2-4 2-4 Chapter 9, Building Feature-Based Grammars 2-4 1-4 Chapter 10, Analyzing th... |
writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of ex... |
The authors provide additional materials for each chapter via the NLTK website at: http://www. nltk. org/ To comment or ask technical questions about this book, send email to: bookquestions@oreilly. com For more information about our books, conferences, Resource Centers, and the O'Reilly Network, see our website at: ht... |
Figure P-1. Edward Loper, Ewan Klein, and Steven Bird, Stanford, July 2007 xx | Preface |
CHAPTER 1 Language Processing and Python It is easy to get our hands on millions of words of text. What can we do with it, assuming we can write some simple programs? In this chapter, we'll address the following questions: 1. What can we achieve by combining simple programming techniques with large quantities of text? ... |
Getting Started with Python One of the friendly things about Python is that it allows you to type directly into the interactive interpreter—the program that will be running your Python programs. You can access the Python interpreter using a simple graphical interface called the In-teractive Deve Lopment Environment (ID... |
>>> 1 + File "<stdin>", line 1 1 + ^ Syntax Error: invalid syntax >>> This produced a syntax error. In Python, it doesn't make sense to end an instruction with a plus sign. The Python interpreter indicates the line where the problem occurred (line 1 of <stdin>, which stands for “standard input”). Now that we can use th... |
tells the interpreter to load some texts for us to explore: from nltk. book import *. This says “from NLTK's book module, load all items. ” The book module contains all the data you will need as you read this chapter. After printing a welcome message, it loads the text of several books (this will take a few seconds). H... |
ght have been rummaged out of this monstrous cabinet there is no telling. But of Whale-Bones ; for Whales of a monstrous size are oftentimes cast up dead u >>> Your Turn: Try searching for other words; to save re-typing, you might be able to use up-arrow, Ctrl-up-arrow, or Alt-p to access the previous command and modif... |
Your Turn: Pick another pair of words and compare their usage in two different texts, using the similar() and common_contexts() functions. It is one thing to automatically detect that a particular word occurs in a text, and to display some words that appear in the same context. However, we can also determine the locati... |
>>> text3. generate() In the beginning of his brother is a hairy man, whose top may reach unto heaven ; and ye shall sow the land of Egypt there was no bread in all that he was taken out of the month, upon the earth. So shall thy wages be ? And they made their father ; and Isaac was old, and kissed him : and Laban with... |
items of text3 with the command: set(text3). When you do this, many screens of words will fly past. Now try the following: >>> sorted(set(text3)) ['!', "'", '(', ')', ',', ',)', '. ', '. )', ':', ';', ';)', '?', '?)', 'A', 'Abel', 'Abelmizraim', 'Abidah', 'Abide', 'Abimael', 'Abimelech', 'Abr', 'Abrah', 'Abraham', 'Abr... |
called a function, and we define a short name for our function with the keyword def. The next example shows how to define two new functions, lexical_diversity() and percentage(): >>> def lexical_diversity(text): ... return len(text) / len(set(text)) ... >>> def percentage(count, total): ... return 100 * count / total..... |
a sense of the power and creativity of programming. Don't worry if you find it a bit confusing right now. Later we'll see how to use functions when tabulating data, as in Table 1-1. Each row of the table will involve the same computation but with different data, and we'll do this repetitive work using a function. Table... |
Some more lists have been defined for you, one for the opening sentence of each of our texts, sent2... sent9. We inspect two of them here; you can see the rest for yourself using the Python interpreter (if you get an error saying that sent2 is not defined, you need to first type from nltk. book import *). >>> sent2 ['T... |
Indexing Lists As we have seen, a text in Python is a list of words, represented using a combination of brackets and quotes. Just as with an ordinary page of text, we can count up the total number of words in text1 with len(text1), and count the occurrences in a text of a particular word—say, heaven—using text1. count(... |
This practice of counting from zero is initially confusing, but typical of modern programming languages. You'll quickly get the hang of it if you've mastered the system of counting centuries where 19XY is a year in the 20th century, or if you live in a country where the floors of a building are numbered from 1, and so ... |
>>> sent[0] = 'First' >>> sent[9] = 'Last' >>> len(sent) 10 >>> sent[1:9] = ['Second', 'Third'] >>> sent ['First', 'Second', 'Third', 'Last'] >>> sent[9] Traceback (most recent call last): File "<stdin>", line 1, in ? Index Error: list index out of range >>> Your Turn: Take a few minutes to define a sentence of your ow... |
Notice in the previous example that we split the definition of my_sent over two lines. Python expressions can be split across multiple lines, so long as this happens within any kind of brackets. Python uses the... prompt to indicate that more input is expected. It doesn't matter how much indentation is used in these co... |
>>> name = 'Monty' >>> name[0] 'M' >>> name[:4] 'Mont' >>> We can also perform multiplication and addition with strings: >>> name * 2 'Monty Monty' >>> name + '!' 'Monty!' >>> We can join the words of a list to make a single string, or split a string into a list, as follows: >>> ' '. join(['Monty', 'Python']) 'Monty Py... |
Frequency Distributions How can we automatically identify the words of a text that are most informative about the topic and genre of the text? Imagine how you might go about finding the 50 most frequent words of a book. One method would be to keep a tally for each vocabulary item, like that shown in Figure 1-3. The tal... |
Your Turn: Try the preceding frequency distribution example for your-self, for text2. Be careful to use the correct parentheses and uppercase letters. If you get an error message Name Error: name 'Freq Dist' is not defined, you need to start your work with from nltk. book import *. Do any words produced in the last exa... |
If the frequent words don't help us, how about the words that occur once only, the so-called hapaxes? View them by typing fdist1. hapaxes(). This list contains lexicographer, cetological, contraband, expostulations, and about 9,000 others. It seems that there are too many rare words, and without seeing the context we p... |
Let's return to our task of finding words that characterize a text. Notice that the long words in text4 reflect its national focus— constitutionally, transcontinental—whereas those in text5 reflect its informal content: boooooooooooglyyyyyy and yuuuuuuuuuuuummmmmmmmmmmm. Have we succeeded in automatically extract-ing w... |
National Government; United Nations; public money >>> text8. collocations() Building collocations list medium build; social drinker; quiet nights; long term; age open; financially secure; fun times; similar interests; Age open; poss rship; single mum; permanent relationship; slim build; seeks lady; Late 30s; Photo pls;... |
differences between authors, genres, or languages. Table 1-2 summarizes the functions defined in frequency distributions. Table 1-2. Functions defined for NLTK's frequency distributions Example Description fdist = Freq Dist(samples) Create a frequency distribution containing the given samples fdist. inc(sample) Increme... |
Operator Relationship != Not equal to > Greater than >= Greater than or equal to We can use these to select different words from a sentence of news text. Here are some examples—notice only the operator is changed from one line to the next. They all use sent7, the first sentence from text7 ( Wall Street Journal ). As be... |
>>> sorted([w for w in set(text1) if w. endswith('ableness')]) ['comfortableness', 'honourableness', 'immutableness', 'indispensableness',... ] >>> sorted([term for term in set(text4) if 'gnt' in term]) ['Sovereignty', 'sovereignties', 'sovereignty'] >>> sorted([item for item in set(text6) if item. istitle()]) ['A', 'A... |
>>> len(set(text1)) 19317 >>> len(set([word. lower() for word in text1])) 17231 >>> Now that we are not double-counting words like This and this, which differ only in capitalization, we've wiped 2,000 off the vocabulary count! We can go a step further and eliminate numbers and punctuation from the vocabulary count by f... |
An if statement is known as a control structure because it controls whether the code in the indented block will be run. Another control structure is the for loop. Try the following, and remember to include the colon and the four spaces: >>> for word in ['Call', 'me', 'Ishmael', '. ']:... print word... Call me Ishmael. ... |
Ishmael is a titlecase word. is punctuation >>> As you can see, even with this small amount of Python knowledge, you can start to build multiline Python programs. It's important to develop such programs in pieces, testing that each piece does what you expect before combining them into a program. This is why the Python ... |
In this section we describe some language understanding technologies, to give you a sense of the interesting challenges that are waiting for you. Word Sense Disambiguation In word sense disambiguation we want to work out which sense of a word was in-tended in a given context. Consider the ambiguous words serve and dish... |
semantic role labeling —identifying how a noun phrase relates to the verb (as agent, patient, instrument, and so on). Generating Language Output If we can automatically solve such problems of language understanding, we will be able to move on to tasks that involve generating language output, such as question answering ... |
then submits the resulting sentence for translation back into English. It stops after 12 iterations, or if it receives a translation that was produced already (indicating a loop): >>> babelize_shell() NLTK Babelizer: type 'help' for a list of commands. Babel> how long before the next flight to Alice Springs? Babel> ger... |
Spoken Dialogue Systems In the history of artificial intelligence, the chief measure of intelligence has been a lin-guistic one, namely the Turing Test : can a dialogue system, responding to a user's text input, perform so naturally that we cannot distinguish it from a human-generated re-sponse? In contrast, today's co... |
Textual Entailment The challenge of language understanding has been brought into focus in recent years by a public “shared task” called Recognizing Textual Entailment (RTE). The basic scenario is simple. Suppose you want to find evidence to support the hypothesis: Sandra Goudie was defeated by Max Purnell, and that you... |
In order to determine whether the hypothesis is supported by the text, the system needs the following background knowledge: (i) if someone is an author of a book, then he/ she has written that book; (ii) if someone is an editor of a book, then he/she has not written (all of) that book; (iii) if someone is editor or aut... |
A function is a block of code that has been assigned a name and can be reused. Functions are defined using the def keyword, as in def mult(x, y); x and y are parameters of the function, and act as placeholders for actual data values. A function is called by specifying its name followed by one or more arguments inside ... |
Some excellent introductory linguistics textbooks are: (Finegan, 2007), (O'Grady et al., 2004), (OSU, 2007). You might like to consult Language Log, a popular linguistics blog with occasional posts that use the techniques described in this book. 1. 8 Exercises 1. ○ Try using the Python interpreter as a calculator, and ... |
whole sentences. What is the relationship between len(phrase1 + phrase2) and len(phrase1) + len(phrase2) ? 12. ○ Consider the following two expressions, which have the same value. Which one will typically be more relevant in NLP? Why? a. "Monty Python"[6:12] b. ["Monty", "Python"][1] 13. ○ We have seen how to represent... |
a. Ending in ize b. Containing the letter z c. Containing the sequence of letters pt d. All lowercase letters except for an initial capital (i. e., titlecase) 25. ◑ Define sent to be the list of words ['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore']. Now write code to perform the following tasks: a. Print... |
CHAPTER 2 Accessing Text Corpora and Lexical Resources Practical work in Natural Language Processing typically uses large bodies of linguistic data, or corpora. The goal of this chapter is to answer the following questions: 1. What are some useful text corpora and lexical resources, and how can we access them with Pyth... |
Gutenberg Corpus NLTK includes a small selection of texts from the Project Gutenberg electronic text archive, which contains some 25,000 free electronic books, hosted at http://www. gu tenberg. org/. We begin by getting the Python interpreter to load the NLTK package, then ask to see nltk. corpus. gutenberg. fileids(),... |
... num_vocab = len(set([w. lower() for w in gutenberg. words(fileid)]))... print int(num_chars/num_words), int(num_words/num_sents), int(num_words/num_vocab), fileid... 4 21 26 austen-emma. txt 4 23 16 austen-persuasion. txt 4 24 22 austen-sense. txt 4 33 79 bible-kjv. txt 4 18 5 blake-poems. txt 4 17 14 bryant-storie... |
Most NLTK corpus readers include a variety of access methods apart from words(), raw(), and sents(). Richer linguistic content is available from some corpora, such as part-of-speech tags, dialogue tags, syntactic trees, and so forth; we will see these in later chapters. Web and Chat Text Although Project Gutenberg cont... |
Table 2-1. Example document for each section of the Brown Corpus ID File Genre Description A16 ca16 news Chicago Tribune: Society Reportage B02 cb02 editorial Christian Science Monitor: Editorials C17 cc17 reviews Time Magazine: Reviews D12 cd12 religion Underwood: Probing the Ethics of Realtors E36 ce36 hobbies Norlin... |
... can: 94 could: 87 may: 93 might: 38 must: 53 will: 389 Your Turn: Choose a different section of the Brown Corpus, and adapt the preceding example to count a selection of wh words, such as what, when, where, who and why. Next, we need to obtain counts for each genre of interest. We'll use NLTK's support for conditio... |
covered by one or more documents, or for the documents included in one or more categories. For convenience, the corpus methods accept a single fileid or a list of fileids. >>> reuters. categories('training/9865') ['barley', 'corn', 'grain', 'wheat'] >>> reuters. categories(['training/9865', 'training/9880']) ['barley',... |
>>> cfd = nltk. Conditional Freq Dist(... (target, file[:4])... for fileid in inaugural. fileids()... for w in inaugural. words(fileid)... for target in ['america', 'citizen']... if w. lower(). startswith(target)) >>> cfd. plot() Figure 2-1. Plot of a conditional frequency distribution: All words in the Inaugural Addre... |
Corpus Compiler Contents Co NLL 2002 Named Entity Co NLL 700k words, POS and named entity tagged (Dutch, Spanish) Co NLL 2007 Dependency Parsed Tree-banks (selections)Co NLL 150k words, dependency parsed (Basque, Catalan) Dependency Treebank Narad Dependency parsed version of Penn Treebank sample Floresta Treebank Dian... |
Corpora in Other Languages NLTK comes with corpora for many languages, though in some cases you will need to learn how to manipulate character encodings in Python before using these corpora (see Section 3. 3). >>> nltk. corpus. cess_esp. words() ['El', 'grupo', 'estatal', 'Electricit\xe9_de_France',... ] >>> nltk. corp... |
Text Corpus Structure We have seen a variety of corpus structures so far; these are summarized in Fig-ure 2-3. The simplest kind lacks any structure: it is just a collection of texts. Often, texts are grouped into categories that might correspond to genre, source, author, lan-guage, etc. Sometimes these categories over... |
Figure 2-3. Common structures for text corpora: The simplest kind of corpus is a collection of isolated texts with no particular organization; some corpora are structured into categories, such as genre (Brown Corpus); some categorizations overlap, such as topic categories (Reuters Corpus); other corpora represent langu... |
['The', 'Adventures', 'of', 'Buster', 'Bear', 'by', 'Thornton', 'W', '. ', 'Burgess', '1920', ']', 'I', 'BUSTER', 'BEAR', 'GOES', 'FISHING', 'Buster', 'Bear'] >>> sents = gutenberg. sents("burgess-busterbrown. txt") >>> sents[1:20] [['I'], ['BUSTER', 'BEAR', 'GOES', 'FISHING'], ['Buster', 'Bear', 'yawned', 'as', 'he', ... |
2. 2 Conditional Frequency Distributions We introduced frequency distributions in Section 1. 3. We saw that given some list mylist of words or other items, Freq Dist(mylist) would compute the number of occurrences of each item in the list. Here we will generalize this idea. When the texts of a corpus are divided into s... |
>>> from nltk. corpus import brown >>> cfd = nltk. Conditional Freq Dist(... (genre, word)... for genre in brown. categories()... for word in brown. words(categories=genre)) Let's break this down, and look at just two genres, news and romance. For each genre , we loop over every word in the genre , producing pairs cons... |
The plot in Figure 2-1 was based on a conditional frequency distribution reproduced in the following code. The condition is either of the words america or citizen , and the counts being plotted are the number of times the word occurred in a particular speech. It exploits the fact that the filename for each speech—for e... |
Your Turn: Working with the news and romance genres from the Brown Corpus, find out which days of the week are most newsworthy, and which are most romantic. Define a variable called days containing a list of days of the week, i. e., ['Monday',... ]. Now tabulate the counts for these words using cfd. tabulate(samples=da... |
text = nltk. corpus. genesis. words('english-kjv. txt') bigrams = nltk. bigrams(text) cfd = nltk. Conditional Freq Dist(bigrams) >>> print cfd['living'] <Freq Dist: 'creature': 7, 'thing': 4, 'substance': 2, ',': 1, '. ': 1, 'soul': 1> >>> generate_model(cfd, 'living') living creature that he said, and the land of the ... |
Save this program in a file called monty. py, then go to the Run menu and select the command Run Module. (We'll learn what modules are shortly. ) The result in the main IDLE window should look like this: >>> ================================ RESTART ================================ >>> Monty Python >>> You can also type... |
>>> from __future__ import division >>> def lexical_diversity(text):... return len(text) / len(set(text)) We use the keyword return to indicate the value that is produced as output by the function. In this example, all the work of the function is done in the return statement. Here's an equivalent definition that does t... |
Modules Over time you will find that you create a variety of useful little text-processing functions, and you end up copying them from old programs to new ones. Which file contains the latest version of the function you want to use? It makes life a lot easier if you can collect your work into a single place, and access... |
the sense definition. Two distinct words having the same spelling are called homonyms. The simplest kind of lexicon is nothing more than a sorted list of words. Sophisticated lexicons include complex structure within and across the individual entries. In this section, we'll look at some lexical resources included with ... |
'actually', 'after', 'afterwards', 'again', 'against', "ain't", 'all', 'allow', 'allows', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always',... ] Let's define a function to compute what fraction of words in a text are not in the stop-words list: >>> def content_fraction(text):... stopwords = nltk. cor... |
>>> names = nltk. corpus. names >>> names. fileids() ['female. txt', 'male. txt'] >>> male_names = names. words('male. txt') >>> female_names = names. words('female. txt') >>> [w for w in male_names if w in female_names] ['Abbey', 'Abbie', 'Abby', 'Addie', 'Adrian', 'Adrien', 'Ajay', 'Alex', 'Alexis', 'Alfie', 'Ali', '... |
A Pronouncing Dictionary A slightly richer kind of lexical resource is a table (or spreadsheet), containing a word plus some properties in each row. NLTK includes the CMU Pronouncing Dictionary for U. S. English, which was designed for use by speech synthesizers. >>> entries = nltk. corpus. cmudict. entries() >>> len(e... |
>>> syllable = ['N', 'IH0', 'K', 'S'] >>> [word for word, pron in entries if pron[-4:] == syllable] ["atlantic's", 'audiotronics', 'avionics', 'beatniks', 'calisthenics', 'centronics', 'chetniks', "clinic's", 'clinics', 'conics', 'cynics', 'diasonics', "dominic's", 'ebonics', 'electronics', "electronics'", 'endotronics... |
P-K pik peek pic pique paque polk perc poke perk pac pock poch purk pak pa... P-L pil poehl pille pehl pol pall pohl pahl paul perl pale paille perle po... P-N paine payne pon pain pin pawn pinn pun pine paign pen pyne pane penn p... P-P pap paap pipp paup pape pup pep poop pop pipe paape popp pip peep pope... P-R paar... |
'here', 'there', 'who', 'what', 'where', 'when', 'how', 'not', 'all', 'many', 'some', 'few', 'other', 'one', 'two', 'three', 'four', 'five', 'big', 'long', 'wide',... ] We can access cognate words from multiple languages using the entries() method, specifying a list of languages. With one further step we can convert th... |
>>> from nltk. corpus import toolbox >>> toolbox. entries('rotokas. dic') [('kaa', [('ps', 'V'), ('pt', 'A'), ('ge', 'gag'), ('tkp', 'nek i pas'), ('dcsv', 'true'), ('vx', '1'), ('sc', '???'), ('dt', '29/Oct/2005'), ('ex', 'Apoka ira kaaroi aioa-ia reoreopaoro. '), ('xp', 'Kaikai i pas long nek bilong Apoka bikos em i ... |
>>> wn. synset('car. n. 01'). lemma_names ['car', 'auto', 'automobile', 'machine', 'motorcar'] Each word of a synset can have several meanings, e. g., car can also signify a train car-riage, a gondola, or an elevator car. However, we are only interested in the single meaning that is common to all words of this synset. ... |
Your Turn: Write down all the senses of the word dish that you can think of. Now, explore this word with the help of Word Net, using the same operations shown earlier. The Word Net Hierarchy Word Net synsets correspond to abstract concepts, and they don't always have corre-sponding words in English. These concepts are ... |
'phaeton', 'police_car', 'police_cruiser', 'prowl_car', 'race_car', 'racer', 'racing_car', 'roadster', 'runabout', 'saloon', 'secondhand_car', 'sedan', 'sport_car', 'sport_utility', 'sport_utility_vehicle', 'sports_car', 'squad_car', 'station_waggon', 'station_wagon', 'stock_car', 'subcompact', 'subcompact_car', 'taxi'... |
>>> wn. synset('tree. n. 01'). member_holonyms() [Synset('forest. n. 01')] To see just how intricate things can get, consider the word mint, which has several closely related senses. We can see that mint. n. 04 is part of mint. n. 02 and the substance from which mint. n. 05 is made. >>> for synset in wn. synsets('mint'... |
Recall that each synset has one or more hypernym paths that link it to a root hypernym such as entity. n. 01. Two synsets linked to the same root may have several hypernyms in common (see Figure 2-8 ). If two synsets share a very specific hypernym—one that is low down in the hypernym hierarchy—they must be closely rela... |
Several other similarity measures are available; you can type help(wn) for more information. NLTK also includes Verb Net, a hierarchical verb lexicon linked to Word Net. It can be accessed with nltk. corpus. verb net. 2. 6 Summary A text corpus is a large, structured collection of texts. NLTK comes with many corpora, e... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 9