Python - 语料库访问



语料库是一个由多个文本文档集合组成的群组。单个集合称为语料库。一个著名的语料库是古登堡语料库,它包含大约 25,000 本免费电子书,网址为 http://www.gutenberg.org/。在下面的示例中,我们访问语料库中仅以 .txt 为扩展名的普通文本文件的文件名称。

from nltk.corpus import gutenberg
fields = gutenberg.fileids()

print(fields)

当我们运行以上程序时,会得到以下输出 -

[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']

访问原始文本

我们可以使用 nltk 中提供的 sent_tokenize 函数访问这些文件的原始文本。在下面的示例中,我们将 blake 诗歌文本的头两个段落检索出来。

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

当我们运行以上程序时,会得到以下输出 -

[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.
广告