Corpus Readers

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. 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

1   Corpus Reader Objects

1.1   Overview

The NLTK data package 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:

 
>>> import nltk.corpus
>>> # The Brown corpus:
>>> print nltk.corpus.brown 
<CategorizedTaggedCorpusReader in '.../corpora/brown'>
>>> # The Penn Treebank Corpus:
>>> print nltk.corpus.treebank 
<BracketParseCorpusReader in '.../corpora/treebank/combined'>
>>> # The Name Genders Corpus:
>>> print nltk.corpus.names 
<WordListCorpusReader in '.../corpora/names'>
>>> print nltk.corpus.inaugural 
<PlaintextCorpusReader in '.../corpora/inaugural'>

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 files() method of the corpus reader:

 
>>> print nltk.corpus.treebank.files() 
('wsj_0001.mrg', 'wsj_0002.mrg', 'wsj_0003.mrg', 'wsj_0004.mrg', ...)
>>> print nltk.corpus.inaugural.files() 
('1789-Washington.txt', '1793-Washington.txt', '1797-Adams.txt', ...)

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.

 
>>> from nltk.corpus import inaugural
>>> inaugural.raw('1789-Washington.txt') 
'Fellow-Citizens of the Senate ...
>>> inaugural.words('1789-Washington.txt')
['Fellow', '-', 'Citizens', 'of', 'the', 'Senate', ...]
>>> inaugural.sents('1789-Washington.txt') 
[['Fellow', '-', 'Citizens'...], ['Among', 'the', 'vicissitudes'...]...]
>>> inaugural.paras('1789-Washington.txt') 
[[['Fellow', '-', 'Citizens'...]],
 [['Among', 'the', 'vicissitudes'...],
  ['On', 'the', 'one', 'hand', ',', 'I'...]...]...]

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.

 
>>> l1 = len(inaugural.words('1789-Washington.txt'))
>>> l2 = len(inaugural.words('1793-Washington.txt'))
>>> l3 = len(inaugural.words(['1789-Washington.txt', '1793-Washington.txt']))
>>> print '%s+%s == %s' % (l1, l2, l3)
1538+147 == 1685

If the reader methods are called without any arguments, they will typically load all documents in the corpus.

 
>>> len(inaugural.words())
143066

1.2   Plaintext Corpora

Here are the first few words from each of NLTK's plaintext corpora:

 
>>> nltk.corpus.abc.words()
['PM', 'denies', 'knowledge', 'of', 'AWB', 'kickbacks', ...]
>>> nltk.corpus.genesis.words()
['In', 'the', 'beginning', 'God', 'created', 'the', ...]
>>> nltk.corpus.gutenberg.words()
['VOLUME', 'I', 'CHAPTER', 'I', 'Emma', 'Woodhouse', ...]
>>> nltk.corpus.inaugural.words()
['Fellow', '-', 'Citizens', 'of', 'the', 'Senate', ...]
>>> nltk.corpus.state_union.words()
['PRESIDENT', 'HARRY', 'S', '.', 'TRUMAN', "'", 'S', ...]
>>> nltk.corpus.udhr.words() 
['\xc0\xf3\xe0\xfe\xfb\xf2\xfa\xfb\xfe\xf1\xe0',
 '\xe8\xe7\xe8\xed6\xfa\xe0', ...]
>>> nltk.corpus.webtext.words()
['White', 'guy', ':', 'So', ',', 'do', 'you', 'have', ...]

1.3   Tagged 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.

 
>>> from nltk.corpus import brown
>>> print brown.words()
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
>>> print brown.tagged_words()
[('The', 'AT'), ('Fulton', 'NP-TL'), ...]
>>> print brown.sents() 
[['The', 'Fulton', 'County'...], ['The', 'jury', 'further'...], ...]
>>> print brown.tagged_sents() 
[[('The', 'AT'), ('Fulton', 'NP-TL')...],
 [('The', 'AT'), ('jury', 'NN'), ('further', 'RBR')...]...]
>>> print brown.paras(categories='c') 
[[['It', 'is', 'not', 'news', 'that', 'Nathan', 'Milstein'...],
  ['Certainly', 'not', 'in', 'Orchestra', 'Hall', 'where'...]],
 [['There', 'was', 'about', 'that', 'song', 'something', ...],
  ['Not', 'the', 'noblest', 'performance', 'we', 'have', ...], ...], ...]
>>> print brown.tagged_paras(categories='c') 
[[[('It', 'PPS'), ('is', 'BEZ'), ('not', '*'), ...],
  [('Certainly', 'RB'), ('not', '*'), ('in', 'IN'), ...]],
 [[('There', 'EX'), ('was', 'BEDZ'), ('about', 'IN'), ...],
  [('Not', '*'), ('the', 'AT'), ('noblest', 'JJT'), ...], ...], ...]

Similarly, the Indian Langauge POS-Tagged Corpus includes samples of Indian text annotated with part-of-speech tags:

 
>>> from nltk.corpus import indian
>>> print indian.words() 
['\xe0\xa6\xae\xe0\xa6\xb9\xe0\xa6\xbf\...',
 '\xe0\xa6\xb8\xe0\xa6\xa8\xe0\xa7\x8d\xe0...', ...]
>>> print indian.tagged_words() 
[('\xe0\xa6\xae\xe0\xa6\xb9\xe0\xa6\xbf...', 'NN'),
 ('\xe0\xa6\xb8\xe0\xa6\xa8\xe0\xa7\x8d\xe0...', 'NN'), ...]

Tagged corpora support access to simplified tags, e.g. where all nouns tags are collapsed to a single category N:

 
>>> print brown.tagged_sents(simplify_tags=True) 
[[('The', 'DET'), ('Fulton', 'NP'), ('County', 'N'), ('Grand', 'ADJ'), ...],
 [('The', 'DET'), ('jury', 'N'), ('further', 'ADV'), ('said', 'VD'), ...]...]

Use nltk.draw.pos-concordance() to access a GUI for searching tagged corpora.

1.4   Chunked 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.

 
>>> from nltk.corpus import conll2000, conll2002
>>> print conll2000.sents() 
[['Confidence', 'in', 'the', 'pound', 'is', 'widely', ...],
 ['Chancellor', 'of', 'the', 'Exchequer', ...], ...]
>>> for tree in conll2000.chunked_sents()[:2]:
...     print tree 
(S
  (NP Confidence/NN)
  (PP in/IN)
  (NP the/DT pound/NN)
  (VP is/VBZ widely/RB expected/VBN to/TO take/VB)
  (NP another/DT sharp/JJ dive/NN)
  if/IN
  ...)
(S
  Chancellor/NNP
  (PP of/IN)
  (NP the/DT Exchequer/NNP)
  ...)
>>> print conll2002.sents() 
[['Sao', 'Paulo', '(', 'Brasil', ')', ',', ...], ['-'], ...]
>>> for tree in conll2002.chunked_sents()[:2]:
...     print tree 
(S
  (LOC Sao/NC Paulo/VMI)
  (/Fpa
  (LOC Brasil/NC)
  )/Fpt
  ...)
(S -/Fg)

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.)

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:

 
>>> from nltk.corpus import ieer
>>> ieer.files() 
('APW_19980314', 'APW_19980424', 'APW_19980429',
 'NYT_19980315', 'NYT_19980403', 'NYT_19980407')
>>> docs = ieer.parsed_docs('APW_19980314')
>>> print docs[0]
<IEERDocument APW19980314.0391: 'Kenyans protest tax hikes'>
>>> print docs[0].docno
APW19980314.0391
>>> print docs[0].doctype
NEWS STORY
>>> print docs[0].date_time
03/14/1998 10:36:00
>>> print docs[0].headline
(DOCUMENT Kenyans protest tax hikes)
>>> print docs[0].text 
(DOCUMENT
  (LOCATION NAIROBI)
  ,
  (LOCATION Kenya)
  (
  (ORGANIZATION AP)
  )
  _
  (CARDINAL Thousands)
  of
  laborers,
  ...
  on
  (DATE Saturday)
  ...)

1.5   Parsed Corpora

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:

 
>>> from nltk.corpus import treebank
>>> print treebank.files() 
('wsj_0001.mrg', 'wsj_0002.mrg', 'wsj_0003.mrg', 'wsj_0004.mrg', ...)
>>> print treebank.words('wsj_0003.mrg')
['A', 'form', 'of', 'asbestos', 'once', 'used', '*', ...]
>>> print treebank.tagged_words('wsj_0003.mrg')
[('A', 'DT'), ('form', 'NN'), ('of', 'IN'), ...]
>>> print treebank.parsed_sents('wsj_0003.mrg')[0] 
(S
  (S-TPC-1
    (NP-SBJ
      (NP (NP (DT A) (NN form)) (PP (IN of) (NP (NN asbestos))))
      (RRC ...)...)...)
  ...
  (VP (VBD reported) (SBAR (-NONE- 0) (S (-NONE- *T*-1))))
  (. .))

Reading the Sinica Treebank:

 
>>> from nltk.corpus import sinica_treebank
>>> print sinica_treebank.sents()
[['\xe4\xb8\x80'], ['\xe5\x8f\x8b\xe6\x83\x85'], ...]
>>> sinica_treebank.parsed_sents()[25] 
Tree('S',
    [Tree('NP',
        [Tree('Nba', ['\xe5\x98\x89\xe7\x8f\x8d'])]),
     Tree('V\xe2\x80\xa7\xe5\x9c\xb0',
        [Tree('VA11', ['\xe4\xb8\x8d\xe5\x81\x9c']),
         Tree('DE', ['\xe7\x9a\x84'])]),
     Tree('VA4', ['\xe5\x93\xad\xe6\xb3\xa3'])])

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:

 
>>> from nltk.corpus import ycoe
>>> for tree in ycoe.parsed_sents('cocuraC')[:4]:
...     print tree 
(CP-THT
  (C +D+atte)
  (IP-SUB ...)
  ...
  (. .))
(IP-MAT
  (IP-MAT-0
    (PP (P On) (NP (ADJ o+dre) (N wisan)))...)
  ...
  (. .))
(IP-MAT
  (NP-NOM-x-2 *exp*)
  (NP-DAT-1 (D^D +D+am) (ADJ^D unge+dyldegum))
  ...
  (. .))
(IP-MAT
  (ADVP (ADV Sw+a))
  (NP-NOM-x (PRO^N hit))
  (ADVP-TMP (ADV^T oft))
  ...
  (. .))

If the YCOE corpus is not available, you will get an error message when you try to access it:

 
>>> from nltk.corpus import ycoe
>>> print ycoe 
Traceback (most recent call last):
LookupError:
**********************************************************************
  Resource 'corpora/ycoe' not found.  For installation
  instructions, please see <http://nltk.org/index.php/Installation>.
  Searched in:
    - ...
**********************************************************************

1.6   Word Lists and Lexicons

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:

 
>>> from nltk.corpus import names, stopwords, words
>>> words.files()
('en', 'en-basic')
>>> words.words('en') 
['Aarhus', 'Aaron', 'Ababa', 'aback', 'abaft', 'abandon', ...]
 
>>> stopwords.files() 
('danish', 'dutch', 'english', 'french', ...)
>>> stopwords.words('english') 
['a', "a's", 'able', 'about', 'above', 'according', ...]
 
>>> names.files()
('female.txt', 'male.txt')
>>> names.words('male.txt') 
['Aamir', 'Aaron', 'Abbey', 'Abbie', 'Abbot', 'Abbott', ...]
>>> names.words('female.txt') 
['Abagael', 'Abagail', 'Abbe', 'Abbey', 'Abbi', 'Abbie', ...]

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.

 
>>> from nltk.corpus import cmudict
>>> print cmudict.entries()[600:605] 
[('ACCOUNTING', 1, ('AH0', 'K', 'AW1', 'N', 'T', 'IH0', 'NG')),
 ('ACCOUNTING', 2, ('AH0', 'K', 'AW1', 'N', 'IH0', 'NG')),
 ('ACCOUNTS', 1, ('AH0', 'K', 'AW1', 'N', 'T', 'S')),
 ('ACCOUTERMENT', 1, ('AH0', 'K', 'UW1', 'T', 'ER0', ...)),
 ('ACCOUTERMENTS', 1, ('AH0', 'K', 'UW1', 'T', 'ER0', ...))]
>>> # Load the entire cmudict corpus into a Python dictionary:
>>> transcr = cmudict.transcriptions()
>>> print [transcr[w][0] for w in 'NATURAL LANGUAGE TOOL KIT'.split()] 
[('N', 'AE1', 'CH', 'ER0', 'AH0', 'L'),
 ('L', 'AE1', 'NG', 'G', 'W', 'AH0', 'JH'),
 ('T', 'UW1', 'L'),
 ('K', 'IH1', 'T')]

1.7   Categorized Corpora

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.:

 
>>> from nltk.corpus import brown, movie_reviews, reuters
>>> brown.categories()
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r']
>>> movie_reviews.categories()
['neg', 'pos']
>>> reuters.categories() 
['acq', 'alum', 'barley', 'bop', 'carcass', 'castor-oil', 'cocoa',
'coconut', 'coconut-oil', 'coffee', 'copper', 'copra-cake', 'corn',
'cotton', 'cotton-oil', 'cpi', 'cpu', 'crude', 'dfl', 'dlr', ...]

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:

 
>>> brown.categories('ca01')
['a']
>>> brown.categories(['ca01','cb01'])
['a', 'b']
>>> reuters.categories('training/9865')
['barley', 'corn', 'grain', 'wheat']
>>> reuters.categories(['training/9865', 'training/9880'])
['barley', 'corn', 'grain', 'money-fx', 'wheat']

We can go back the other way using the optional argument of the files() method:

 
>>> reuters.files('barley') 
['test/15618', 'test/15649', 'test/15676', 'test/15728', 'test/15871', ...]

Both the categories() and files() 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 files, we can identify one or more categories, e.g.:

 
>>> brown.tagged_words(categories='a')
[('The', 'AT'), ('Fulton', 'NP-TL'), ...]
>>> brown.sents(categories=['b','c']) 
[['Assembly', 'session', 'brought', 'much', 'good'], ['The', 'General',
'Assembly', ',', 'which', 'adjourns', 'today', ',', 'has', 'performed',
'in', 'an', 'atmosphere', 'of', 'crisis', 'and', 'struggle', 'from',
'the', 'day', 'it', 'convened', '.'], ...]

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:

 
>>> def classify(doc): return 'a'   # Trivial classifier
>>> doc = 'ca01'
>>> classify(doc) in brown.categories(doc)
True

1.8   Propbank Corpus

The Propbank corpus provides predicate-argument annotation for the entire treebank. Each verb in the treebank is annotated by a single instance in the propbank corpus, containing information about the location of the verb, and the location and identity of its arguments:

 
>>> from nltk.corpus import propbank
>>> pb_instances = propbank.instances()
>>> print pb_instances 
[<PropbankInstance: wsj_0001.mrg, sent 0, word 8>,
 <PropbankInstance: wsj_0001.mrg, sent 1, word 10>, ...]

Each propbank instance defines the following member variables:

  • Location information: filename, sentnum, wordnum
  • Annotator information: tagger
  • Inflection information: inflection
  • Roleset identifier: roleset
  • Verb (aka predicate) location: predicate
  • Argument locations and types: arguments

The following examples show the types of these arguments:

 
>>> inst = pb_instances[103]
>>> (inst.filename, inst.sentnum, inst.wordnum)
('wsj_0004.mrg', 8, 16)
>>> inst.tagger
'gold'
>>> inst.inflection
<PropbankInflection: vp--a>
>>> infl = inst.inflection
>>> infl.form, infl.tense, infl.aspect, infl.person, infl.voice
('v', 'p', '-', '-', 'a')
>>> inst.roleset
'rise.01'
>>> inst.predicate
PropbankTreePointer(16, 0)
>>> inst.arguments 
((PropbankTreePointer(0, 2), 'ARG1'),
 (PropbankTreePointer(13, 1), 'ARGM-DIS'),
 (PropbankTreePointer(17, 1), 'ARG4-to'),
 (PropbankTreePointer(20, 1), 'ARG3-from'))

The location of the predicate and of the arguments are encoded using PropbankTreePointer objects, as well as PropbankChainTreePointer objects and PropbankSplitTreePointer objects. A PropbankTreePointer consists of a wordnum and a height:

 
>>> print inst.predicate.wordnum, inst.predicate.height
16 0

This identifies the tree constituent that is headed by the word that is the wordnum'th token in the sentence, and whose span is found by going height nodes up in the tree. This type of pointer is only useful if we also have the corresponding tree structure, since it includes empty elements such as traces in the word number count. The trees for 10% of the standard propbank corpus are contained in the treebank corpus:

 
>>> tree = inst.tree
 
>>> from nltk.corpus import treebank
>>> assert tree == treebank.parsed_sents(inst.filename)[inst.sentnum]
 
>>> inst.predicate.select(tree)
Tree('VBD', ['rose'])
>>> for (argloc, argid) in inst.arguments:
...     print '%-10s %s' % (argid, argloc.select(tree).pprint(500)[:50])
ARG1       (NP-SBJ (NP (DT The) (NN yield)) (PP (IN on) (NP (
ARGM-DIS   (PP (IN for) (NP (NN example)))
ARG4-to    (PP-DIR (TO to) (NP (CD 8.04) (NN %)))
ARG3-from  (PP-DIR (IN from) (NP (CD 7.90) (NN %)))

Propbank tree pointers can be converted to standard tree locations, which are usually easier to work with, using the treepos() method:

 
>>> treepos = inst.predicate.treepos(tree)
>>> print treepos, tree[treepos]
(4, 0) (VBD rose)

In some cases, argument locations will be encoded using PropbankChainTreePointers (for trace chains) or PropbankSplitTreePointers (for discontinuous constituents). Both of these objects contain a single member variable, pieces, containing a list of the constituent pieces. They also define the method select(), which will return a tree containing all the elements of the argument. (A new head node is created, labeled "CHAIN" or "SPLIT", since the argument is not a single constituent in the original tree). Sentence #6 contains an example of an argument that is both discontinuous and contains a chain:

 
>>> inst = pb_instances[6]
>>> inst.roleset
'expose.01'
>>> argloc, argid = inst.arguments[2]
>>> argloc
<PropbankChainTreePointer: 22:1,24:0,25:1*27:0>
>>> argloc.pieces
[<PropbankSplitTreePointer: 22:1,24:0,25:1>, PropbankTreePointer(27, 0)]
>>> argloc.pieces[0].pieces
[PropbankTreePointer(22, 1), PropbankTreePointer(24, 0),
 PropbankTreePointer(25, 1)]
>>> print argloc.select(inst.tree)
(*CHAIN*
  (*SPLIT* (NP (DT a) (NN group)) (IN of) (NP (NNS workers)))
  (-NONE- *))

The propbank corpus also provides access to the frameset files, which define the argument labels used by the annotations, on a per-verb basis. Each frameset file contains one or more predicates, such as 'turn' or 'turn_on', each of which is divided into coarse-grained word senses called rolesets. For each roleset, the frameset file provides descriptions of the argument roles, along with examples.

 
>>> expose_01 = propbank.roleset('expose.01')
>>> turn_01 = propbank.roleset('turn.01')
>>> print turn_01 
<Element roleset at ...>
>>> for role in turn_01.findall("roles/role"):
...     print role.attrib['n'], role.attrib['descr']
0 turner
1 thing turning
m direction, location
 
>>> from nltk.etree import ElementTree
>>> print ElementTree.tostring(turn_01.find('example')).strip()
<example name="transitive agentive">
  <text>
  John turned the key in the lock.
  </text>
  <arg n="0">John</arg>
  <rel>turned</rel>
  <arg n="1">the key</arg>
  <arg f="LOC" n="m">in the lock</arg>
</example>

Note that the standard corpus distribution only contains 10% of the treebank, so the parse trees are not availalbe for instances starting at 9353:

 
>>> inst = pb_instances[9352]
>>> inst.filename
'wsj_0199.mrg'
>>> print inst.tree 
(S (NP-SBJ (NNP Trinity)) (VP (VBD said) (SBAR (-NONE- 0) ...))
>>> print inst.predicate.select(inst.tree)
(VB begin)
 
>>> inst = pb_instances[9353]
>>> inst.filename
'wsj_0200.mrg'
>>> print inst.tree
None
>>> print inst.predicate.select(inst.tree)
Traceback (most recent call last):
  . . .
ValueError: Parse tree not avaialable

However, if you supply your own version of the treebank corpus (by putting it before the nltk-provided version on nltk.data.path), then you can access the trees for all instances.

A list of the verb lemmas contained in propbank is returned by the propbank.verbs() method:

 
>>> propbank.verbs()
['abandon', 'abate', 'abdicate', 'abet', 'abide', ...]

1.9   Other Corpora

1.9.1   senseval

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.

 
>>> from nltk.corpus import senseval
>>> senseval.files()
('hard.pos', 'interest.pos', 'line.pos', 'serve.pos')
>>> senseval.instances('hard.pos')
[SensevalInstance(word='hard-a',
    position=20,
    context=[('``', '``'), ('he', 'PRP'), ...('hard', 'JJ'), ...],
    senses=('HARD1',)),
 SensevalInstance(word='hard-a',
    position=10,
    context=[('clever', 'NNP'), ...('hard', 'JJ'), ('time', 'NN'), ...],
    senses=('HARD1',)), ...]

The following code looks at instances of the word 'interest', and displays their local context (2 words on each side) and word sense(s):

 
>>> for inst in senseval.instances('interest.pos')[:10]:
...     p = inst.position
...     left = ' '.join(w for (w,t) in inst.context[p-2:p])
...     word = ' '.join(w for (w,t) in inst.context[p:p+1])
...     right = ' '.join(w for (w,t) in inst.context[p+1:p+3])
...     senses = ' '.join(inst.senses)
...     print '%20s |%10s | %-15s -> %s' % (left, word, right, senses)
         declines in |  interest | rates .         -> interest_6
  indicate declining |  interest | rates because   -> interest_6
       in short-term |  interest | rates .         -> interest_6
                 4 % |  interest | in this         -> interest_5
        company with | interests | in the          -> interest_5
              , plus |  interest | .               -> interest_6
             set the |  interest | rate on         -> interest_6
              's own |  interest | , prompted      -> interest_4
       principal and |  interest | is the          -> interest_6
        increase its |  interest | to 70           -> interest_5

1.9.2   ppattach

The Prepositional Phrase Attachment corpus is a corpus of prepositional phrase attachment decisions. Each instance in the corpus is encoded as a PPAttachment object:

 
>>> from nltk.corpus import ppattach
>>> ppattach.attachments('training') 
[PPAttachment(sent='0', verb='join', noun1='board',
              prep='as', noun2='director', attachment='V'),
 PPAttachment(sent='1', verb='is', noun1='chairman',
              prep='of', noun2='N.V.', attachment='N'),
 ...]
>>> inst = ppattach.attachments('training')[0]
>>> (inst.sent, inst.verb, inst.noun1, inst.prep, inst.noun2)
('0', 'join', 'board', 'as', 'director')
>>> inst.attachment
'V'

1.9.3   shakespeare

The Shakespeare corpus contains a set of Shakespeare plays, formatted as XML files. These corpora are returned as ElementTree objects:

 
>>> from nltk.corpus import shakespeare
>>> from nltk.etree import ElementTree
>>> shakespeare.files() 
('a_and_c.xml', 'dream.xml', 'hamlet.xml', 'j_caesar.xml', ...)
>>> play = shakespeare.xml('dream.xml')
>>> print play 
<Element 'PLAY' at ...>
>>> print '%s: %s' % (play[0].tag, play[0].text)
TITLE: A Midsummer Night's Dream
>>> personae = [persona.text for persona in
...             play.findall('PERSONAE/PERSONA')]
>>> print personae 
['THESEUS, Duke of Athens.', 'EGEUS, father to Hermia.', ...]
>>> # Find and print speakers not listed as personae
>>> names = [persona.split(',')[0] for persona in personae]
>>> speakers = set(speaker.text for speaker in
...                play.findall('*/*/*/SPEAKER'))
>>> print sorted(speakers.difference(names)) 
['ALL', 'COBWEB', 'DEMETRIUS', 'Fairy', 'HERNIA', 'LYSANDER',
 'Lion', 'MOTH', 'MUSTARDSEED', 'Moonshine', 'PEASEBLOSSOM',
 'Prologue', 'Pyramus', 'Thisbe', 'Wall']

1.9.4   toolbox

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.

 
>>> from nltk.corpus import toolbox
>>> from nltk.etree import ElementTree
>>> from nltk.probability import FreqDist
>>> import re
>>> rotokas = toolbox.xml('rotokas.dic')
>>> redup_pos_freqdist = FreqDist()
>>> # Note: we skip over the first record, which is actually
>>> # the header.
>>> for record in rotokas[1:]:
...     lexeme = record.find('lx').text
...     if re.match(r'(.*)\1$', lexeme):
...         redup_pos_freqdist.inc(record.find('ps').text)
>>> for item in redup_pos_freqdist.sorted():
...     print item, redup_pos_freqdist[item]
V 41
N 14
??? 4

This example displays some records from a Rotokas text:

 
>>> river = toolbox.xml('rotokas/river.txt', key='ref')
>>> for record in river.findall('record')[:3]:
...     for piece in record:
...         if len(piece.text) > 60:
...             print '%-6s %s...' % (piece.tag, piece.text[:57])
...         else:
...             print '%-6s %s' % (piece.tag, piece.text)
ref    Paragraph 1
t      ``Viapau oisio              ra   ovaupasi                ...
m      viapau   oisio              ra   ovau   -pa       -si    ...
g      NEG      this way/like this and  forget -PROG     -2/3.DL...
p      NEG      ???                CONJ V.I    -SUFF.V.3 -SUFF.V...
f      ``No ken lus tingting wanema samting papa i bin tok,'' Na...
fe     ``Don't forget what Dad said,'' yelled Naomi.
ref    2
t      Osa     Ira  ora  Reviti viapau uvupasiva.
m      osa     Ira  ora  Reviti viapau uvu        -pa       -si ...
g      as/like name and  name   NEG    hear/smell -PROG     -2/3...
p      CONJ    N.PN CONJ N.PN   NEG    V.T        -SUFF.V.3 -SUF...
f      Tasol Ila na David no bin harim toktok.
fe     But Ila and David took no notice.
ref    3
t      Ikaupaoro                     rokosiva                   ...
m      ikau      -pa       -oro      roko    -si       -va      ...
g      run/hurry -PROG     -SIM      go down -2/3.DL.M -RP      ...
p      V.T       -SUFF.V.3 -SUFF.V.4 ADV     -SUFF.V.4 -SUFF.VT....
f      Tupela i bin hariap i go long wara .
fe     They raced to the river.

1.9.5   timit

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.

 
>>> from nltk.corpus import timit
>>> print timit.utterances() 
('dr1-fvmh0/sa1', 'dr1-fvmh0/sa2', 'dr1-fvmh0/si1466',
 'dr1-fvmh0/si2096', 'dr1-fvmh0/si836', 'dr1-fvmh0/sx116',
 'dr1-fvmh0/sx206', 'dr1-fvmh0/sx26', 'dr1-fvmh0/sx296', ...)
 
>>> item = timit.utterances()[5]
>>> print timit.phones(item) 
['h#', 'k', 'l', 'ae', 's', 'pcl', 'p', 'dh', 'ax',
 's', 'kcl', 'k', 'r', 'ux', 'ix', 'nx', 'y', 'ax',
 'l', 'eh', 'f', 'tcl', 't', 'hh', 'ae', 'n', 'dcl',
 'd', 'h#']
>>> print timit.words(item)
['clasp', 'the', 'screw', 'in', 'your', 'left', 'hand']
>>> timit.play(item) 

The corpus reader can combine the word segmentation information with the phonemes to produce a single tree structure:

 
>>> for tree in timit.phone_trees(item):
...     print tree
(S
  h#
  (clasp k l ae s pcl p)
  (the dh ax)
  (screw s kcl k r ux)
  (in ix nx)
  (your y ax)
  (left l eh f tcl t)
  (hand hh ae n dcl d)
  h#)

The start time and stop time of each phoneme, word, and sentence are also available:

 
>>> print timit.phone_times(item) 
[('h#', 0, 2190), ('k', 2190, 3430), ('l', 3430, 4326), ...]
>>> print timit.word_times(item) 
[('clasp', 2190, 8804), ('the', 8804, 9734), ...]
>>> print timit.sent_times(item)
[('Clasp the screw in your left hand.', 0, 32154)]

We can use these times to play selected pieces of a speech sample:

 
>>> timit.play(item, 2190, 8804) # 'clasp'  

The corpus reader can also be queried for information about the speaker and sentence identifier for a given speech sample:

 
>>> print timit.spkrid(item)
dr1-fvmh0
>>> print timit.sentid(item)
sx116
>>> print timit.spkrinfo(timit.spkrid(item)) 
SpeakerInfo(id='VMH0',
            sex='F',
            dr='1',
            use='TRN',
            recdate='03/11/86',
            birthdate='01/08/60',
            ht='5\'05"',
            race='WHT',
            edu='BS',
            comments='BEST NEW ENGLAND ACCENT SO FAR')
 
>>> # List the speech samples from the same speaker:
>>> timit.utterances(spkrid=timit.spkrid(item)) 
('dr1-fvmh0/sa1', 'dr1-fvmh0/sa2', 'dr1-fvmh0/si1466', ...)

1.9.6   rte

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.

 
>>> from nltk.corpus import rte
>>> print rte.files() 
('rte1_dev.xml', 'rte1_test.xml', 'rte2_dev.xml', ..., 'rte3_test.xml')
>>> rtepairs = rte.pairs('rte2_test.xml')
>>> print rtepairs  
[<RTEPair: gid=2-8>, <RTEPair: gid=2-9>, <RTEPair: gid=2-15>, ...]

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).

 
>>> rtepairs[5]
<RTEPair: gid=2-23>
>>> rtepairs[5].text 
'His wife Strida won a seat in parliament after forging an alliance
with the main anti-Syrian coalition in the recent election.'
>>> rtepairs[5].hyp
'Strida elected to parliament.'
>>> rtepairs[5].value
1

The RTE corpus also supports an xml() method which produces ElementTrees.

 
>>> xmltree = rte.xml('rte3_dev.xml')
>>> xmltree 
<Element entailment-corpus at ...>
>>> xmltree[7].findtext('t') 
"Mrs. Bush's approval ratings have remained very high, above 80%,
even as her husband's have recently dropped below 50%."

1.9.7   verbnet

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:

 
>>> from nltk.corpus import verbnet
>>> verbnet.lemmas()[20:25]
['accelerate', 'accept', 'acclaim', 'accompany', 'accrue']
>>> verbnet.classids()[:5]
['accompany-51_7', 'admire-31.2-1', 'admire-31_2', 'admit-65', 'adopt-93']

The classids() method may also be used to retrieve the classes that a given lemma belongs to:

 
>>> verbnet.classids('accept')
['approve-77', 'characterize-29.2-1-1', 'obtain-13_5_2']

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:

 
>>> verbnet.vnclass('remove-10.1') 
<Element 'VNCLASS' at ...>

The vnclass() method also accepts "short" identifiers, such as '10.1':

 
>>> verbnet.vnclass('10.1') 
<Element 'VNCLASS' at ...>

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:

 
>>> vn_31_2 = verbnet.vnclass('admire-31.2')
>>> for themrole in vn_31_2.findall('THEMROLES/THEMROLE'):
...     print themrole.attrib['type'],
...     for selrestr in themrole.findall('SELRESTRS/SELRESTR'):
...         print '[%(Value)s%(type)s]' % selrestr.attrib,
...     print
Theme
Experiencer [+animate]
Predicate

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():

 
>>> print verbnet.pprint('57')
weather-57
  Subclasses: (none)
  Members: blow clear drizzle fog freeze gust hail howl lightning mist
    mizzle pelt pour precipitate rain roar shower sleet snow spit spot
    sprinkle storm swelter teem thaw thunder
  Thematic roles:
    * Theme[+concrete +force]
  Frames:
    Intransitive (Expletive Subject)
      Syntax: LEX[it] LEX[[+be]] VERB
      Semantics:
        * weather(during(E), Weather_type, ?Theme)
    NP (Expletive Subject, Theme Object)
      Syntax: LEX[it] LEX[[+be]] VERB NP[Theme]
      Semantics:
        * weather(during(E), Weather_type, Theme)
    PP (Expletive Subject, Theme-PP)
      Syntax: LEX[it[+be]] VERB PREP[with] NP[Theme]
      Semantics:
        * weather(during(E), Weather_type, Theme)

1.9.8   nps_chat

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.

 
>>> print nltk.corpus.nps_chat.words()
['now', 'im', 'left', 'with', 'this', 'gay', 'name', ...]
>>> print nltk.corpus.nps_chat.tagged_words()
[('now', 'RB'), ('im', 'PRP'), ('left', 'VBD'), ...]
>>> print nltk.corpus.nps_chat.tagged_posts() 
[[('now', 'RB'), ('im', 'PRP'), ('left', 'VBD'), ('with', 'IN'),
('this', 'DT'), ('gay', 'JJ'), ('name', 'NN')], [(':P', 'UH')], ...]

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.

 
>>> print nltk.corpus.nps_chat.xml_posts() 
[<Element 'Post' at 0x...>, <Element 'Post' at 0x...>, ...]
>>> posts = nltk.corpus.nps_chat.xml_posts()
>>> nltk.FreqDist(p.attrib['class'] for p in posts).sorted() 
['Statement', 'System', 'Greet', 'Emotion', 'ynQuestion',
'whQuestion', 'Accept', 'Bye', 'Emphasis', 'Continuer',
'Reject', 'yAnswer', 'nAnswer', 'Clarify', 'Other']
>>> posts[0].text
'now im left with this gay name'

In addition to the above methods for accessing tagged text, we can navigate the XML structure directly, as follows:

 
>>> tokens = posts[0].findall('terminals/t')
>>> [t.attrib['pos'] + "/" + t.attrib['word'] for t in tokens]
['RB/now', 'PRP/im', 'VBD/left', 'IN/with', 'DT/this', 'JJ/gay', 'NN/name']

2   Corpus Reader Classes

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.

2.1   Automatically Created Corpus Reader Instances

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:

 
>>> import nltk
>>> nltk.corpus.brown 
<CategorizedTaggedCorpusReader in '.../corpora/brown'>
>>> nltk.corpus.treebank 
<BracketParseCorpusReader in '.../corpora/treebank/combined'>
>>> nltk.corpus.names 
<WordListCorpusReader in '.../corpora/names'>
>>> nltk.corpus.genesis 
<PlaintextCorpusReader in '.../corpora/genesis'>
>>> nltk.corpus.inaugural 
<PlaintextCorpusReader in '.../corpora/inaugural'>

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).

2.2   Creating New Corpus Reader Instances

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 access a corpus that is not included in the NLTK data distribution.
  • To access a full copy of a corpus for which the NLTK data distribution only provides a sample.
  • To access a corpus using a customized corpus reader (e.g., with a customized tokenizer).

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:

 
>>> # Find the directory where the corpus lives.
>>> genesis_dir = nltk.data.find('corpora/genesis')
>>> # Create our custom sentence tokenizer.
>>> my_sent_tokenizer = nltk.RegexpTokenizer('[^.!?]+')
>>> # Create the new corpus reader object.
>>> my_genesis = nltk.corpus.PlaintextCorpusReader(
...     genesis_dir, '.*\.txt', sent_tokenizer=my_sent_tokenizer)
>>> # Use the new corpus reader object.
>>> print my_genesis.sents('english-kjv.txt')[0] 
['In', 'the', 'beginning', 'God', 'created', 'the', 'heaven',
 'and', 'the', 'earth']

For a complete list of corpus reader subclasses, see the API documentation for nltk.corpus.CorpusReader.

2.3   Corpus Types

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:

  • A token corpus contains information about specific occurences of language use (or linguistic tokens), such as dialogues or written texts. Examples of token corpora are collections of written text and collections of speech.
  • A type corpus, or lexicon, contains information about a coherent set of lexical items (or linguistic types). Examples of lexicons are dictionaries and word lists.
  • A language description corpus contains information about a set of non-lexical linguistic constructs, such as grammar rules.

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.

2.4   Common Corpus Reader Methods

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:

 
>>> print nltk.corpus.genesis.root 
/.../corpora/genesis

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:

 
>>> some_corpus_file_id = nltk.corpus.reuters.files()[0]
>>> import os.path
>>> os.path.join(*some_corpus_file_id.split('/'))
'test/14826'

To get a list of all data files that make up a corpus, use the files() method. In some corpora, these files will not all contain the same type of data; for example, for the nltk.corpus.timit corpus, files() 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 files() 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:

 
>>> nltk.corpus.timit.files() 
('dr1-fvmh0/sa1.phn', 'dr1-fvmh0/sa1.txt', 'dr1-fvmh0/sa1.wav', ...)
>>> nltk.corpus.timit.files('phn') 
['dr1-fvmh0/sa1.phn', 'dr1-fvmh0/sa2.phn', 'dr1-fvmh0/si1466.phn', ...]

In some corpora, the files are divided into distinct categories. For these corpora, the files() method takes an optional argument, which can be used to get a list of the files within a specific category:

 
>>> nltk.corpus.brown.files('e') 
['ce01', 'ce02', 'ce03', 'ce04', 'ce05', 'ce06', 'ce07', ...]

The abspath() method can be used to find the absolute path to a corpus file, given its file identifier:

 
>>> nltk.corpus.brown.abspath('ce06') 
FileSystemPathPointer('.../corpora/brown/ce06')

The abspaths() method can be used to find the absolute paths for one corpus file, a list of corpus files, or all corpus files, depending on its argument type:

 
>>> nltk.corpus.brown.abspaths() 
[FileSystemPathPointer('.../corpora/brown/ca01'),
 FileSystemPathPointer('.../corpora/brown/ca02'), ...]
>>> nltk.corpus.brown.abspaths('ce06') 
[FileSystemPathPointer('.../corpora/brown/ce06')]
>>> nltk.corpus.brown.abspaths(['ce06', 'ce07']) 
[FileSystemPathPointer('.../corpora/brown/ce06'),
 FileSystemPathPointer('.../corpora/brown/ce07')]

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).

2.5   Data Access Methods

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(files=None, ...options...)

Where files 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:

 
>>> nltk.corpus.brown.words()
['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', ...]
>>> nltk.corpus.treebank.words()
['Pierre', 'Vinken', ',', '61', 'years', 'old', ',', ...]
>>> nltk.corpus.conll2002.words()
['Sao', 'Paulo', '(', 'Brasil', ')', ',', '23', 'may', ...]
>>> nltk.corpus.genesis.words()
['In', 'the', 'beginning', 'God', 'created', 'the', ...]

On the other hand, the tagged_words() method is only supported by corpora that include part-of-speech annotations: