TypeError:切片索引必须是整数或无或具有__index__方法NLP

时间:2018-04-11 08:45:26

标签: python nlp nltk

我正在运行NLP的示例,使用词干分析器函数作为类方法。

import nltk

class IndexedText(object):
    def __init__(self, stemmer, text):
        self._text = text 
        self._stemmer = stemmer
        self._index = nltk.Index((self._stem(word), i) for (i, word) in enumerate(text))
    def concordance(self, word, width=40):
        key = self._stem(word)
        wc = width/4 # words of context 
        print (self._index[key])
        for i in self._index[key]:
            lcontext = ' '.join(self._text[i-wc:i]) 
            rcontext = ' '.join(self._text[i:i+wc]) 
            ldisplay = '%*s' % (width, lcontext[-width:]) 
            rdisplay = '%-*s' % (width, rcontext[:width]) 
            print (ldisplay, rdisplay)
    def _stem(self, word):
        return self._stemmer.stem(word).lower()



 porter = nltk.PorterStemmer()

 grail = nltk.corpus.webtext.words('grail.txt')

 text = IndexedText(porter, grail)

现在我在单词'谎言'上使用了一致性功能。如下:

text.concordance('lie')

它给我的错误如下:

TypeError: slice indices must be integers or None or have an __index__ method

索引['谎言']在哪里产生所有整数的输出: [1824,6451,7038,7080,8450,13860,13965,16684]

1 个答案:

答案 0 :(得分:0)

我注意到了一些内容:

lcontext = ' '.join(self._text[i-wc:i])

这里的“i”类型似乎是一个元组。你可能要修改它。