Python Get Corpus
Getting a Corpus with Python
A corpus is a collection of text documents. A collection is called a corpus. One well-known corpus is the Gutenberg Corpus, which contains approximately 25,000 free e-books and is hosted at http://www.gutenberg.org/. In the following example, we only access the names of plain text files whose names end in .txt.
from nltk.corpus import gutenberg
fields = gutenberg.fileids()
print(fields)
When we run the above program, we get the following output −
[austen-emma.txt', austen-persuasion.txt', austen-sense.txt', bible-kjv.txt',
blake-poems.txt', bryant-stories.txt', burgess-busterbrown.txt',
carroll-alice.txt', chesterton-ball.txt', chesterton-brown.txt',
chesterton-thursday.txt', edgeworth-parents.txt', melville-moby_dick.txt',
milton-paradise.txt', shakespeare-caesar.txt', shakespeare-hamlet.txt',
shakespeare-macbeth.txt', whitman-leaves.txt']
Accessing the Raw Text
We can access the raw text from these files using the sent_tokenize function, also available in nltk. In the example below, we retrieve the first two paragraphs of Blake’s poem.
from nltk.tokenize import sent_tokenize
from nltk.corpus import gutenberg
sample = gutenberg.raw("blake-poems.txt")
token = sent_tokenize(sample)
for para in range(2):
print(token[para])
When we run the above program, we will get the following output –
[Poems by William Blake 1789]
SONGS OF INNOCENCE AND OF EXPERIENCE
and THE BOOK of THEL
SONGS OF INNOCENCE
INTRODUCTION
Piping down the valleys wild,
Piping songs of pleasant glee,
On a cloud I saw a child,
And he laughing said to me:
"Pipe a song about a Lamb!"
So I piped with Merry cheer.