The nltk.corpus package defines a collection of corpus reader classes, which can be used to access the contents of a diverse set of corpora. The list of available corpora is given at:
http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml
Each corpus reader class is specialized to handle a specific corpus format. In addition, the nltk.corpus package automatically creates a set of corpus reader instances that can be used to access the corpora in the NLTK data package. Section 1 ("Corpus Reader Objects") describes the corpus reader instances that can be used to read the corpora in the NLTK data package. Section 2 ("Corpus Reader Classes") describes the corpus reader classes themselves, and discusses the issues involved in creating new corpus reader objects and new corpus reader classes. Section 3 ("Regression Tests") contains regression tests for the corpus readers and associated functions and classes.
Table of Contents
NLTK includes a diverse set of corpora which can be read using the nltk.corpus package. Each corpus is accessed by means of a "corpus reader" object from nltk.corpus:
|
Most corpora consist of a set of files, each containing a document (or other pieces of text). A list of identifiers for these files is accessed via the fileids() method of the corpus reader:
|
Each corpus reader provides a variety of methods to read data from the corpus, depending on the format of the corpus. For example, plaintext corpora support methods to read the corpus as raw text, a list of words, a list of sentences, or a list of paragraphs.
|
Each of these reader methods may be given a single document's item name or a list of document item names. When given a list of document item names, the reader methods will concatenate together the contents of the individual documents.
|
If the reader methods are called without any arguments, they will typically load all documents in the corpus.
|
If a corpus contains a README file, it can be accessed with a readme() method:
|
Here are the first few words from each of NLTK's plaintext corpora:
|
In addition to the plaintext corpora, NLTK's data package also contains a wide variety of annotated corpora. For example, the Brown Corpus is annotated with part-of-speech tags, and defines additional methods tagged_*() which words as (word,tag) tuples, rather than just bare word strings.
|
Similarly, the Indian Langauge POS-Tagged Corpus includes samples of Indian text annotated with part-of-speech tags:
|
Several tagged corpora support access to a simplified, universal tagset, e.g. where all nouns tags are collapsed to a single category NOUN:
|
Use nltk.app.pos_concordance() to access a GUI for searching tagged corpora.
The CoNLL corpora also provide chunk structures, which are encoded as flat trees. The CoNLL 2000 Corpus includes phrasal chunks; and the CoNLL 2002 Corpus includes named entity chunks.
|
Note
Since the CONLL corpora do not contain paragraph break information, these readers do not support the para() method.)
Warning
if you call the conll corpora reader methods without any arguments, they will return the contents of the entire corpus, including the 'test' portions of the corpus.)
SemCor is a subset of the Brown corpus tagged with WordNet senses and named entities. Both kinds of lexical items include multiword units, which are encoded as chunks (senses and part-of-speech tags pertain to the entire chunk).
|
The IEER corpus is another chunked corpus. This corpus is unusual in that each corpus item contains multiple documents. (This reflects the fact that each corpus file contains multiple documents.) The IEER corpus defines the parsed_docs method, which returns the documents in a given item as IEERDocument objects:
|
The Treebank corpora provide a syntactic parse for each sentence. The NLTK data package includes a 10% sample of the Penn Treebank (in treebank), as well as the Sinica Treebank (in sinica_treebank).
Reading the Penn Treebank (Wall Street Journal sample):
|
If you have access to a full installation of the Penn Treebank, NLTK can be configured to load it as well. Download the ptb package, and in the directory nltk_data/corpora/ptb place the BROWN and WSJ directories of the Treebank installation (symlinks work as well). Then use the ptb module instead of treebank:
|
...and so forth, like treebank but with extended fileids. Categories specified in allcats.txt can be used to filter by genre; they consist of news (for WSJ articles) and names of the Brown subcategories (fiction, humor, romance, etc.):
|
As PropBank and NomBank depend on the (WSJ portion of the) Penn Treebank, the modules propbank_ptb and nombank_ptb are provided for access to a full PTB installation.
Reading the Sinica Treebank:
|
Reading the CoNLL 2007 Dependency Treebanks:
|
NLTK also provides a corpus reader for the York-Toronto-Helsinki Parsed Corpus of Old English Prose (YCOE); but the corpus itself is not included in the NLTK data package. If you install it yourself, you can use NLTK to access it:
|
If the YCOE corpus is not available, you will get an error message when you try to access it:
|
The NLTK data package also includes a number of lexicons and word lists. These are accessed just like text corpora. The following examples illustrate the use of the wordlist corpora:
|
|
The CMU Pronunciation Dictionary corpus contains pronounciation transcriptions for over 100,000 words. It can be accessed as a list of entries (where each entry consists of a word, an identifier, and a transcription) or as a dictionary from words to lists of transcriptions. Transcriptions are encoded as tuples of phoneme strings.
|
Please see the separate WordNet howto.
Please see the separate FrameNet howto.
Please see the separate PropBank howto.
Please see the separate SentiWordNet howto.
Several corpora included with NLTK contain documents that have been categorized for topic, genre, polarity, etc. In addition to the standard corpus interface, these corpora provide access to the list of categories and the mapping between the documents and their categories (in both directions). Access the categories using the categories() method, e.g.:
|
This method has an optional argument that specifies a document or a list of documents, allowing us to map from (one or more) documents to (one or more) categories:
|
We can go back the other way using the optional argument of the fileids() method:
|
Both the categories() and fileids() methods return a sorted list containing no duplicates.
In addition to mapping between categories and documents, these corpora permit direct access to their contents via the categories. Instead of accessing a subset of a corpus by specifying one or more fileids, we can identify one or more categories, e.g.:
|
Note that it is an error to specify both documents and categories.
In the context of a text categorization system, we can easily test if the category assigned to a document is correct as follows:
|
The Senseval 2 corpus is a word sense disambiguation corpus. Each item in the corpus corresponds to a single ambiguous word. For each of these words, the corpus contains a list of instances, corresponding to occurences of that word. Each instance provides the word; a list of word senses that apply to the word occurrence; and the word's context.
|
The following code looks at instances of the word 'interest', and displays their local context (2 words on each side) and word sense(s):
|
The Prepositional Phrase Attachment corpus is a corpus of prepositional phrase attachment decisions. Each instance in the corpus is encoded as a PPAttachment object:
|
The Brown Corpus, annotated with WordNet senses.
|
The Shakespeare corpus contains a set of Shakespeare plays, formatted as XML files. These corpora are returned as ElementTree objects:
|
The Toolbox corpus distributed with NLTK contains a sample lexicon and several sample texts from the Rotokas language. The Toolbox corpus reader returns Toolbox files as XML ElementTree objects. The following example loads the Rotokas dictionary, and figures out the distribution of part-of-speech tags for reduplicated words.
This example displays some records from a Rotokas text:
The NLTK data package includes a fragment of the TIMIT Acoustic-Phonetic Continuous Speech Corpus. This corpus is broken down into small speech samples, each of which is available as a wave file, a phonetic transcription, and a tokenized word list.
|
|
The corpus reader can combine the word segmentation information with the phonemes to produce a single tree structure:
|
The start time and stop time of each phoneme, word, and sentence are also available:
|
We can use these times to play selected pieces of a speech sample:
|
The corpus reader can also be queried for information about the speaker and sentence identifier for a given speech sample:
|
|
The RTE (Recognizing Textual Entailment) corpus was derived from the RTE1, RTE2 and RTE3 datasets (dev and test data), and consists of a list of XML-formatted 'text'/'hypothesis' pairs.
|
In the gold standard test sets, each pair is labeled according to whether or not the text 'entails' the hypothesis; the entailment value is mapped to an integer 1 (True) or 0 (False).
|
The RTE corpus also supports an xml() method which produces ElementTrees.
|
The VerbNet corpus is a lexicon that divides verbs into classes, based on their syntax-semantics linking behavior. The basic elements in the lexicon are verb lemmas, such as 'abandon' and 'accept', and verb classes, which have identifiers such as 'remove-10.1' and 'admire-31.2-1'. These class identifiers consist of a representitive verb selected from the class, followed by a numerical identifier. The list of verb lemmas, and the list of class identifiers, can be retrieved with the following methods:
|
The classids() method may also be used to retrieve the classes that a given lemma belongs to:
|
The primary object in the lexicon is a class record, which is stored as an ElementTree xml object. The class record for a given class identifier is returned by the vnclass() method:
|
The vnclass() method also accepts "short" identifiers, such as '10.1':
|
See the Verbnet documentation, or the Verbnet files, for information about the structure of this xml. As an example, we can retrieve a list of thematic roles for a given Verbnet class:
|
The Verbnet corpus also provides a variety of pretty printing functions that can be used to display the xml contents in a more consise form. The simplest such method is pprint():
|
The NPS Chat Corpus, Release 1.0 consists of over 10,000 posts in age-specific chat rooms, which have been anonymized, POS-tagged and dialogue-act tagged.
|
We can access the XML elements corresponding to individual posts. These elements have class and user attributes that we can access using p.attrib['class'] and p.attrib['user']. They also have text content, accessed using p.text.
|
In addition to the above methods for accessing tagged text, we can navigate the XML structure directly, as follows:
|
NLTK's corpus reader classes are used to access the contents of a diverse set of corpora. Each corpus reader class is specialized to handle a specific corpus format. Examples include the PlaintextCorpusReader, which handles corpora that consist of a set of unannotated text files, and the BracketParseCorpusReader, which handles corpora that consist of files containing parenthesis-delineated parse trees.
When then nltk.corpus module is imported, it automatically creates a set of corpus reader instances that can be used to access the corpora in the NLTK data distribution. Here is a small sample of those corpus reader instances:
|
This sample illustrates that different corpus reader classes are used to read different corpora; but that the same corpus reader class may be used for more than one corpus (e.g., genesis and inaugural).
Although the nltk.corpus module automatically creates corpus reader instances for the corpora in the NLTK data distribution, you may sometimes need to create your own corpus reader. In particular, you would need to create your own corpus reader if you want...
To create a new corpus reader, you will first need to look up the signature for that corpus reader's constructor. Different corpus readers have different constructor signatures, but most of the constructor signatures have the basic form:
SomeCorpusReader(root, files, ...options...)
Where root is an absolute path to the directory containing the corpus data files; files is either a list of file names (relative to root) or a regexp specifying which files should be included; and options are additional reader-specific options. For example, we can create a customized corpus reader for the genesis corpus that uses a different sentence tokenizer as follows:
|
If you wish to read your own plaintext corpus, which is stored in the directory '/usr/share/some-corpus', then you can create a corpus reader for it with:
>>> my_corpus = nltk.corpus.PlaintextCorpusReader( ... '/usr/share/some-corpus', '.*\.txt') # doctest: +SKIP
For a complete list of corpus reader subclasses, see the API documentation for nltk.corpus.CorpusReader.
Corpora vary widely in the types of content they include. This is reflected in the fact that the base class CorpusReader only defines a few general-purpose methods for listing and accessing the files that make up a corpus. It is up to the subclasses to define data access methods that provide access to the information in the corpus. However, corpus reader subclasses should be consistent in their definitions of these data access methods wherever possible.
At a high level, corpora can be divided into three basic types:
However, many individual corpora blur the distinctions between these types. For example, corpora that are primarily lexicons may include token data in the form of example sentences; and corpora that are primarily token corpora may be accompanied by one or more word lists or other lexical data sets.
Because corpora vary so widely in their information content, we have decided that it would not be wise to use separate corpus reader base classes for different corpus types. Instead, we simply try to make the corpus readers consistent wherever possible, but let them differ where the underlying data itself differs.
As mentioned above, there are only a handful of methods that all corpus readers are guaranteed to implement. These methods provide access to the files that contain the corpus data. Every corpus is assumed to consist of one or more files, all located in a common root directory (or in subdirectories of that root directory). The absolute path to the root directory is stored in the root property:
|
Each file within the corpus is identified by a platform-independent identifier, which is basically a path string that uses / as the path seperator. I.e., this identifier can be converted to a relative path as follows:
|
To get a list of all data files that make up a corpus, use the fileids() method. In some corpora, these files will not all contain the same type of data; for example, for the nltk.corpus.timit corpus, fileids() will return a list including text files, word segmentation files, phonetic transcription files, sound files, and metadata files. For corpora with diverse file types, the fileids() method will often take one or more optional arguments, which can be used to get a list of the files with a specific file type:
|
In some corpora, the files are divided into distinct categories. For these corpora, the fileids() method takes an optional argument, which can be used to get a list of the files within a specific category:
|
The abspath() method can be used to find the absolute path to a corpus file, given its file identifier:
|
The abspaths() method can be used to find the absolute paths for one corpus file, a list of corpus files, or (if no fileids are specified), all corpus files.
This method is mainly useful as a helper method when defining corpus data access methods, since data access methods can usually be called with a string argument (to get a view for a specific file), with a list argument (to get a view for a specific list of files), or with no argument (to get a view for the whole corpus).
Individual corpus reader subclasses typically extend this basic set of file-access methods with one or more data access methods, which provide easy access to the data contained in the corpus. The signatures for data access methods often have the basic form:
corpus_reader.some_data access(fileids=None, ...options...)
Where fileids can be a single file identifier string (to get a view for a specific file); a list of file identifier strings (to get a view for a specific list of files); or None (to get a view for the entire corpus). Some of the common data access methods, and their return types, are:
- I{corpus}.words(): list of str
- I{corpus}.sents(): list of (list of str)
- I{corpus}.paras(): list of (list of (list of str))
- I{corpus}.tagged_words(): list of (str,str) tuple
- I{corpus}.tagged_sents(): list of (list of (str,str))
- I{corpus}.tagged_paras(): list of (list of (list of (str,str)))
- I{corpus}.chunked_sents(): list of (Tree w/ (str,str) leaves)
- I{corpus}.parsed_sents(): list of (Tree with str leaves)
- I{corpus}.parsed_paras(): list of (list of (Tree with str leaves))
- I{corpus}.xml(): A single xml ElementTree
- I{corpus}.raw(): str (unprocessed corpus contents)
For example, the words() method is supported by many different corpora, and returns a flat list of word strings:
|
On the other hand, the tagged_words() method is only supported by corpora that include part-of-speech annotations:
|
Although most corpus readers use file identifiers to index their content, some corpora use different identifiers instead. For example, the data access methods for the timit corpus uses utterance identifiers to select which corpus items should be returned:
|
Attempting to call timit's data access methods with a file identifier will result in an exception:
|
As another example, the propbank corpus defines the roleset() method, which expects a roleset identifier, not a file identifier:
|
An important feature of NLTK's corpus readers is that many of them access the underlying data files using "corpus views." A corpus view is an object that acts like a simple data structure (such as a list), but does not store the data elements in memory; instead, data elements are read from the underlying data files on an as-needed basis.
By only loading items from the file on an as-needesd basis, corpus views maintain both memory efficiency and responsiveness. The memory efficiency of corpus readers is important because some corpora contain very large amounts of data, and storing the entire data set in memory could overwhelm many machines. The responsiveness is important when experimenting with corpora in interactive sessions and in in-class demonstrations.
The most common corpus view is the StreamBackedCorpusView, which acts as a read-only list of tokens. Two additional corpus view classes, ConcatenatedCorpusView and LazySubsequence, make it possible to create concatenations and take slices of StreamBackedCorpusView objects without actually storing the resulting list-like object's elements in memory.
In the future, we may add additional corpus views that act like other basic data structures, such as dictionaries.
In order to add support for new corpus formats, it is necessary to define new corpus reader classes. For many corpus formats, writing new corpus readers is relatively streight-forward. In this section, we'll describe what's involved in creating a new corpus reader. If you do create a new corpus reader, we encourage you to contribute it back to the NLTK project.
Before you start writing a new corpus reader, you should check to be sure that the desired format can't be read using an existing corpus reader with appropriate constructor arguments. For example, although the TaggedCorpusReader assumes that words and tags are separated by / characters by default, an alternative tag-separation character can be specified via the sep constructor argument. You should also check whether the new corpus format can be handled by subclassing an existing corpus reader, and tweaking a few methods or variables.
If you decide to write a new corpus reader from scratch, then you should first decide which data access methods you want the reader to provide, and what their signatures should be. You should look at existing corpus readers that process corpora with similar data contents, and try to be consistent with those corpus readers whenever possible.
You should also consider what sets of identifiers are appropriate for the corpus format. Where it's practical, file identifiers should be used. However, for some corpora, it may make sense to use additional sets of identifiers. Each set of identifiers should have a distinct name (e.g., fileids, utteranceids, rolesets); and you should be consistent in using that name to refer to that identifier. Do not use parameter names like id, which leave it unclear what type of identifier is required.
Once you've decided what data access methods and identifiers are appropriate for your corpus, you should decide if there are any customizable parameters that you'd like the corpus reader to handle. These parameters make it possible to use a single corpus reader to handle a wider variety of corpora. The sep argument for TaggedCorpusReader, mentioned above, is an example of a customizable corpus reader parameter.
If your corpus reader implements any customizable parameters, then you'll need to override the constructor. Typically, the new constructor will first call its base class's constructor, and then store the customizable parameters. For example, the ConllChunkCorpusReader's constructor is defined as follows:
|
If your corpus reader does not implement any customization parameters, then you can often just inherit the base class's constructor.
The most common type of data access method takes an argument identifying which files to access, and returns a view covering those files. This argument may be a a single file identifier string (to get a view for a specific file); a list of file identifier strings (to get a view for a specific list of files); or None (to get a view for the entire corpus). The method's implementation converts this argument to a list of path names using the abspaths() method, which handles all three value types (string, list, and None):
|
An example of this type of method is the words() method, defined by the PlaintextCorpusReader as follows:
|
This method first uses abspaths() to convert fileids to a list of absolute paths. It then creates a corpus view for each file, using the PlaintextCorpusReader._read_word_block() method to read elements from the data file (see the discussion of corpus views below). Finally, it combines these corpus views using the nltk.corpus.reader.util.concat() function.
When writing a corpus reader for a corpus that is never expected to be very large, it can sometimes be appropriate to read the files directly, rather than using a corpus view. For example, the WordListCorpusView class defines its words() method as follows:
|
(This is usually more appropriate for lexicons than for token corpora.)
If the type of data returned by a data access method is one for which NLTK has a conventional representation (e.g., words, tagged words, and parse trees), then you should use that representation. Otherwise, you may find it necessary to define your own representation. For data structures that are relatively corpus-specific, it's usually best to define new classes for these elements. For example, the propbank corpus defines the PropbankInstance class to store the semantic role labeling instances described by the corpus; and the ppattach corpus defines the PPAttachment class to store the prepositional attachment instances described by the corpus.
The heart of a StreamBackedCorpusView is its block reader function, which reads zero or more tokens from a stream, and returns them as a list. A very simple example of a block reader is:
|
This simple block reader reads a single line at a time, and returns a single token (consisting of a string) for each whitespace-separated substring on the line. A StreamBackedCorpusView built from this block reader will act like a read-only list of all the whitespace-seperated tokens in an underlying file.
When deciding how to define the block reader for a given corpus, careful consideration should be given to the size of blocks handled by the block reader. Smaller block sizes will increase the memory requirements of the corpus view's internal data structures (by 2 integers per block). On the other hand, larger block sizes may decrease performance for random access to the corpus. (But note that larger block sizes will not decrease performance for iteration.)
Internally, the StreamBackedCorpusView class maintains a partial mapping from token index to file position, with one entry per block. When a token with a given index i is requested, the corpus view constructs it as follows:
The toknum/filepos mapping is created lazily: it is initially empty, but every time a new block is read, the block's initial token is added to the mapping. (Thus, the toknum/filepos map has one entry per block.)
You can create your own corpus view in one of two ways:
The first option is usually easier, but the second option can allow you to write a single read_block method whose behavior can be customized by different parameters to the subclass's constructor. For an example of this design pattern, see the TaggedCorpusView class, which is used by TaggedCorpusView.
The following helper functions are used to create and then delete testing corpora that are stored in temporary directories. These testing corpora are used to make sure the readers work correctly.
|
The plaintext corpus reader is used to access corpora that consist of unprocessed plaintext data. It assumes that paragraph breaks are indicated by blank lines. Sentences and words can be tokenized using the default tokenizers, or by custom tokenizers specificed as parameters to the constructor.
|
|
The list of documents can be specified explicitly, or implicitly (using a regexp). The ext argument specifies a file extension.
|
The directory containing the corpus is corpus.root:
|
We can get a list of words, or the raw string:
|
Check that reading individual documents works, and reading all documents at once works:
|
We're done with the test corpus:
|
Test the plaintext corpora that come with nltk:
|
The Tagged Corpus reader can give us words, sentences, and paragraphs, each tagged or untagged. All of the read methods can take one item (in which case they return the contents of that file) or a list of documents (in which case they concatenate the contents of those files). By default, they apply to all documents in the corpus.
|
|
The Brown Corpus uses the tagged corpus reader:
|
Make sure we're picking up the right number of elements:
|
Selecting classids based on various selectors:
|
vnclass() accepts filenames, long ids, and short ids:
|
fileids() can be used to get files based on verbnet class ids:
|
longid() and shortid() can be used to convert identifiers:
|
Select some corpus files to play with:
|
Check that concatenation works as intended.
|
|
|
|
|
First, do some tests with fairly small slices. These will all generate tuple values.
|
Choose a list of indices, based on the length, that covers the important corner cases:
|
Test slicing with explicit start & stop value:
|
Test slicing with stop=None:
|
Test slicing with start=None:
|
Test slicing with start=stop=None:
|
Next, we'll do some tests with much longer slices. These will generate LazySubsequence objects.
|
Choose a list of indices, based on the length, that covers the important corner cases:
|
Test slicing with explicit start & stop value:
|
Test slicing with stop=None:
|
Test slicing with start=None:
|
Test slicing with start=stop=None:
|
If multiple iterators are created for the same corpus view, their iteration can be interleaved:
|
The file-like objects provided by the codecs module unfortunately suffer from a bug that prevents them from working correctly with corpus view objects. In particular, although the expose seek() and tell() methods, those methods do not exhibit the expected behavior, because they are not synchronized with the internal buffers that are kept by the file-like objects. For example, the tell() method will return the file position at the end of the buffers (whose contents have not yet been returned by the stream); and therefore this file position can not be used to return to the 'current' location in the stream (since seek() has no way to reconstruct the buffers).
To get around these problems, we define a new class, SeekableUnicodeStreamReader, to act as a file-like interface to files containing encoded unicode data. This class is loosely based on the codecs.StreamReader class. To construct a new reader, we call the constructor with an underlying stream and an encoding name:
|
SeekableUnicodeStreamReaders support all of the normal operations supplied by a read-only stream. Note that all of the read operations return unicode objects (not str objects).
|
The size argument to read() specifies the maximum number of bytes to read, not the maximum number of characters. Thus, for encodings that use multiple bytes per character, it may return fewer characters than the size argument:
|
If a read block ends in the middle of the byte string encoding a single character, then that byte string is stored in an internal buffer, and re-used on the next call to read(). However, if the size argument is too small to read even a single character, even though at least one character is available, then the read() method will read additional bytes until it can return a single character. This ensures that the read() method does not return an empty string, which could be mistaken for indicating the end of the file.
|
The readline() method may read more than a single line of text, in which case it stores the text that it does not return in a buffer. If this buffer is not empty, then its contents will be included in the value returned by the next call to read(), regardless of the size argument, since they are available without reading any new bytes from the stream:
|
In addition to these basic read operations, SeekableUnicodeStreamReader also supports the seek() and tell() operations. However, some care must still be taken when using these operations. In particular, the only file offsets that should be passed to seek() are 0 and any offset that has been returned by tell.
|
The seek() and tell() methods work property even when readline() is used.
|
svn 5276 fixed a bug in the comment-stripping behavior of parse_sexpr_block.
|
svn 5277 fixed a bug in parse_sexpr_block, which would cause it to enter an infinite loop if a file ended mid-sexpr, or ended with a token that was not followed by whitespace. A related bug caused an infinite loop if the corpus ended in an unmatched close paren -- this was fixed in svn 5279
|
|
|
svn 5624 & 5265 fixed a bug in ConcatenatedCorpusView, which caused it to return the wrong items when indexed starting at any index beyond the first file.
|
svn 5728 fixed a bug in Categorized*CorpusReader, which caused them to return words from all files when just one file was specified.
|
svn 7227 fixed a bug in the qc corpus reader, which prevented access to its tuples() method
|