6

我正在阅读这个精彩的教程

我下载了一个名为book

>>> import nltk
>>> nltk.download()

和导入的文本:

>>> from nltk.book import *
*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811

然后我可以对这些文本运行命令:

>>> text1.concordance("monstrous")

如何在我自己的数据集上运行这些 nltk 命令?这些集合是否与bookpython中的对象相同?

4

2 回答 2

4

你是对的,很难找到book.py模块的文档。因此,我们必须亲自动手并查看代码(请参见此处)。看看 ,book.py用 book 模块做协调和所有花哨的东西:

首先,您必须将原始文本放入 nltk 的corpus类中,有关详细信息,请参阅使用 NLTK 创建新语料库。

其次,您将语料库单词读入 NLTK 的Text课程中​​。然后您可以使用您在http://nltk.org/book/ch01.html中看到的功能

from nltk.corpus import PlaintextCorpusReader
from nltk.text import Text

# For example, I create an example text file
text1 = '''
This is a story about a foo bar. Foo likes to go to the bar and his last name is also bar. At home, he kept a lot of gold chocolate bars.
'''
text2 = '''
One day, foo went to the bar in his neighborhood and was shot down by a sheep, a blah blah black sheep.
'''
# Creating the corpus
corpusdir = './mycorpus/' 
with (corpusdir+'text1.txt','w') as fout:
    fout.write(text1)
with (corpusdir+'text2.txt','w') as fout:
    fout.write(text2, fout)

# Read the the example corpus into NLTK's corpus class.
mycorpus = PlaintextCorpusReader(corpusdir, '.*')

# Read the NLTK's corpus into NLTK's text class, 
# where your book-like concoordance search is available
mytext = Text(mycorpus.words())

mytext.concoordance('foo')

注意:您可以使用其他 NLTK 的 CorpusReaders,甚至可以指定自定义段落/句子/单词标记器和编码,但现在,我们将坚持使用默认值

于 2013-07-19T10:12:27.367 回答
2

使用来自 bogs.princeton.edu 的 NLTK 备忘单进行文本分析 https://blogs.princeton.edu/etc/files/2014/03/Text-Analysis-with-NLTK-Cheatsheet.pdf

使用您自己的文本:

打开文件进行阅读

file = open('myfile.txt') 

在启动 Python 之前,请确保您位于正确的目录中 - 或提供完整的路径规范。

阅读文件:

t = file.read() 

标记文本:

tokens = nltk.word_tokenize(t)

转换为 NLTK 文本对象:

text = nltk.Text(tokens)
于 2015-03-31T16:52:47.577 回答