【问题标题】:How do I use the book functions (e.g. concoordance) in NLTK?如何在 NLTK 中使用书籍功能(例如协调)?
【发布时间】:2013-07-18 21:47:38
【问题描述】:

我正在处理这个wonderful tutorial

我下载了一个名为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一样吗?

【问题讨论】:

  • 请注意,当您只需要 nltk.book 函数时,可能不需要 import nltk

标签: python nlp nltk


【解决方案1】:

您说得对,很难找到book.py 模块的文档。所以我们必须亲自动手并查看代码(参见here)。查看book.py,使用书籍模块进行协调和所有花哨的东西:

首先您必须将原始文本放入 nltk 的 corpus 类中,有关详细信息,请参阅 Creating a new corpus with 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 的 CorpusReader,甚至可以指定自定义段落/句子/单词标记器和编码,但现在,我们将坚持使用默认值

【讨论】:

  • 其他人请注意...上面有用的示例代码有一些(微不足道的)错误,所以不要按字面意思使用它或陷入对每个细节的理解。
  • 啊,有一些非常古老的 C 代码风格,比如来自旧 Python 的编码风格,让我编辑一下 =)
【解决方案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)

【讨论】:

  • 链接导致页面未找到错误......太糟糕了,我很高兴看到它。
猜你喜欢
  • 2021-04-30
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-15
  • 1970-01-01
相关资源
最近更新 更多