调用NLTK的一致性 - 如何在使用的单词之前/之后获取文本?

时间:2012-01-17 16:25:57

标签: python nltk

我想知道在concordace返回的实例之后会出现什么文本。因此,举例来说,如果你看一下他们在'Searching Text' section中给出的例子,他们会得到“怪异”这个词的一致性。你会怎么得到一个怪异事件之后的话?

1 个答案:

答案 0 :(得分:20)

import nltk
import nltk.book as book
text1 = book.text1
c = nltk.ConcordanceIndex(text1.tokens, key = lambda s: s.lower())
print([text1.tokens[offset+1] for offset in c.offsets('monstrous')])

产量

['size', 'bulk', 'clubs', 'cannibal', 'and', 'fable', 'Pictures', 'pictures', 'stories', 'cabinet', 'size']

我通过查找如何定义concordance方法找到了这个。

这表明text1.concordance中定义了/usr/lib/python2.7/dist-packages/nltk/text.py

In [107]: text1.concordance?
Type:       instancemethod
Base Class: <type 'instancemethod'>
String Form:    <bound method Text.concordance of <Text: Moby Dick by Herman Melville 1851>>
Namespace:  Interactive
File:       /usr/lib/python2.7/dist-packages/nltk/text.py

在该文件中,您将找到

def concordance(self, word, width=79, lines=25):
    ... 
        self._concordance_index = ConcordanceIndex(self.tokens,
                                                   key=lambda s:s.lower())
    ...            
    self._concordance_index.print_concordance(word, width, lines)

这显示了如何实例化ConcordanceIndex个对象。

在同一档案中你也会发现:

class ConcordanceIndex(object):
    def __init__(self, tokens, key=lambda x:x):
        ...
    def print_concordance(self, word, width=75, lines=25):
        ...
        offsets = self.offsets(word)
        ...
        right = ' '.join(self._tokens[i+1:i+context])

通过IPython解释器中的一些实验,这显示self.offsets('monstrous')给出了可以找到单词monstrous的数字列表(偏移量)。您可以使用self._tokens[offset]访问实际的字词,这与text1.tokens[offset]相同。

monstrous给出了text1.tokens[offset+1]之后的下一个字。