Why do I encountered AttributeError: 'WordListCorpusReader' object has no attribute 'word' in python?

Why do I encountered AttributeError: 'WordListCorpusReader' object has no attribute 'word' in python?

下面是我尝试编码出来的方法。但是,在代码的第 3 行中它表示存在属性错误并且 'WordListCorpusReader' 对象在 python 中没有属性 'word'。请帮我看看下面的代码:((

'''step 3. conduct preprocessing steps'''

# setting up the resources for the preprocessing steps
stop = set(stopwords.word('english'))
exclude = set(string.punctuation)
lemma = WordNetLemmatizer()

def clean(doc):
    stop_free = ''.join([i for i in doc.lower().split() if i not in stop])
    punc_free = ''.join([ch for ch in stop_free if ch not in exclude])
    normalized = ''.join(wn.lemma.lemmatize(word) for word in punc_free.split())
    return normalized
    doc_clean = [clean(doc).split() for doc in corpus]
    '''step 4. prepare word representation'''
    dictionary = corpora.Dictionary(doc_clean)
    doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]
    '''step 5. create lda model'''
    topic_num = 5
    word_num = 5
    Lda = gensim.models.ldamodel.LdaModel
    ldamodel = Lda(doc_term_matrix, num_topics=topic_num, id2word=dictionary, passes=20)
    pprint(ldamodel.print_topics(num_topics=topic_num, num_words=word_num))

这是运行代码后的追溯:

Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/topicmodel/topicmodel.py", line 41, in <module>
    stop = set(stopwords.word('english'))
  File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\nltk\corpus\util.py", line 119, in __getattr__
    return getattr(self, attr)
AttributeError: 'WordListCorpusReader' object has no attribute 'word'

打错了。您应该调用的方法是 stopwords.words()。更改:

stop = set(stopwords.word('english'))

进入

stop = set(stopwords.words('english'))

这应该可以解决这个问题。

有关 NLTK 文档页面的更多信息: https://www.nltk.org/api/nltk.corpus.html?highlight=corpus#module-nltk.corpus