我正在通过这个精彩的教程。
我下载了一个名为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命令?这些集合与python中的对象book 相同吗?
发布于 2013-07-19 10:12:27
您是对的,很难找到book.py模块的文档。因此,我们必须弄脏我们的手,看看代码,(参见这里)。看看book.py,来完成图书模块的协调和所有花哨的内容:
首先,您必须将原始文本放到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,甚至可以指定自定义的段落/句子/单词标记器和编码,但是现在,我们将坚持默认的
发布于 2015-03-31 16:52:47
基于 https://blogs.princeton.edu/etc/files/2014/03/Text-Analysis-with-NLTK-Cheatsheet.pdf的NLTK文本分析
使用您自己的文本:
打开文件以读取
file = open('myfile.txt') 在启动Python之前,确保您位于正确的目录中--或者给出完整的路径规范。
阅读文件:
t = file.read() 标记文本:
tokens = nltk.word_tokenize(t)转换为NLTK文本对象:
text = nltk.Text(tokens)https://stackoverflow.com/questions/17734534
复制相似问题