首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在NLTK中使用图书函数(例如concoordance)?

如何在NLTK中使用图书函数(例如concoordance)?
EN

Stack Overflow用户
提问于 2013-07-18 21:47:38
回答 2查看 1.2K关注 0票数 6

我正在通过这个精彩的教程

我下载了一个名为book的集合

代码语言:javascript
运行
复制
>>> import nltk
>>> nltk.download()

和进口文本:

代码语言:javascript
运行
复制
>>> 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

然后,我可以在这些文本上运行命令:

代码语言:javascript
运行
复制
>>> text1.concordance("monstrous")

如何在我自己的数据集中运行这些nltk命令?这些集合与python中的对象book 相同吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-19 10:12:27

您是对的,很难找到book.py模块的文档。因此,我们必须弄脏我们的手,看看代码,(参见这里)。看看book.py,来完成图书模块的协调和所有花哨的内容:

首先,您必须将原始文本放到nltk的corpus类中,有关更多细节,请参见使用NLTK创建新的语料库

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

代码语言:javascript
运行
复制
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,甚至可以指定自定义的段落/句子/单词标记器和编码,但是现在,我们将坚持默认的

票数 4
EN

Stack Overflow用户

发布于 2015-03-31 16:52:47

基于 https://blogs.princeton.edu/etc/files/2014/03/Text-Analysis-with-NLTK-Cheatsheet.pdf的NLTK文本分析

使用您自己的文本:

打开文件以读取

代码语言:javascript
运行
复制
file = open('myfile.txt') 

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

阅读文件:

代码语言:javascript
运行
复制
t = file.read() 

标记文本:

代码语言:javascript
运行
复制
tokens = nltk.word_tokenize(t)

转换为NLTK文本对象:

代码语言:javascript
运行
复制
text = nltk.Text(tokens)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17734534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档