[英]TypeError: slice indices must be integers or None or have an __index__ method NLP
I am running an example for NLP, using a stemmer function as a class method. 我正在使用词干函数作为类方法来运行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)
Now i'm using concordance function on word 'lie' as follows : 现在我在单词'lie'上使用一致函数,如下所示:
text.concordance('lie')
And it gives me the error as below : 它给了我如下错误:
TypeError: slice indices must be integers or None or have an __index__ method
Where as the index['lie'] yields the output as all integers : [1824, 6451, 7038, 7080, 8450, 13860, 13965, 16684] 其中,当index ['lie']产生所有整数形式的输出时:[1824,6451,7038,7080,8450,13860,13965,16684]
I noticed something in the line : 我注意到一行中的内容:
lcontext = ' '.join(self._text[i-wc:i])
the type of "i" here seems to be a tuple. 这里的“ i”类型似乎是一个元组。 you might have to modify it.
您可能需要对其进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.