【问题标题】:TypeError: slice indices must be integers or None or have an __index__ method NLPTypeError:切片索引必须是整数或无或具有 __index__ 方法 NLP
【发布时间】:2018-09-21 01:41:05
【问题描述】:

我正在运行一个 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

其中 index['lie'] 将输出作为所有整数产生: [1824、6451、7038、7080、8450、13860、13965、16684]

【问题讨论】:

    标签: python nlp nltk


    【解决方案1】:

    我注意到一行中有一些东西:

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

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

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 2015-04-01
      • 2017-10-16
      • 2018-06-06
      • 2020-07-01
      • 2021-08-21
      • 1970-01-01
      • 2014-01-11
      • 2022-08-11
      相关资源
      最近更新 更多