对不起,我还是解决不了这个None的问题。我正在使用 NMF 算法来获取语料库的主题,然后尝试检索每个主题所附的文档。但没有人能阻止我!当我尝试检索文档时出现错误
脚本:
import pandas
import numpy as np
import pandas as pd
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import TfidfVectorizer
def display_topics(model, feature_names, n_top_words):
for topic_idx, topic in enumerate(model.components_):
print "Topic %d:" % (topic_idx)
print " ".join([feature_names[i] for i in topic.argsort()[:-n_top_words - 1:-1]])
text = pandas.read_csv('pretraitement_virgile.csv', encoding = 'utf-8')
good_text = text['phrase']
bad_text = text['raw_phrase']
bad_text_list = bad_text.values.tolist()
good_text_list = good_text.values.tolist()
tfidf_vectorizer = TfidfVectorizer()
tfidf = tfidf_vectorizer.fit_transform(good_text_list)
tfidf_feature_names = tfidf_vectorizer.get_feature_names()
topics_number = 3
# Run NMF
nmf = NMF(n_components=topics_number, random_state=1, alpha=.1, l1_ratio=.5, init='nndsvd').fit(tfidf)
document_topics = nmf.fit_transform(tfidf)
n_top_words = 10
print 'NMF topics'
topics = display_topics(nmf, tfidf_feature_names, n_top_words)
print topics
print
print 'Documents per topic'
for topic in range(len(topics)):
if topic == None:
pass
else:
print("Topic {}:".format(topic))
docs = np.argsort(document_topics[:, topic])[::-1]
for mail in docs[:3]:
bad_text_list_n = " ".join(bad_text_list[mail].split(",")[:2])
print (" ".join(good_text_list[mail].split(",")[:2]) + ',' + bad_text_list_n)
我试图设置一个忽略名称的条件,但它不起作用。我仍然有同样的错误。
Topic 0:
order cancel delivery date not want store always well ahead
Topic 1:
product not broken only package arrived received color color delivered
Topic 2:
product not return site store receipt order available in advance
None
Documents par topic
Traceback (most recent call last): File "NMF.py", line 49, in for topic in range(len(topics)):
TypeError: object of type 'NoneType' has no len()
我需要这个结果:
Topic 0:
order cancel delivery date not want store always well ahead
Topic 1:
product not broken only package arrived received color color delivered
Topic 2:
product not return site store receipt order available in advance
Documents par topic
Topic 0:
text text text
text text text
text text text
Topic 1:
text text text
text text text
text text text
Topic 2:
text text text
text text text
text text text
一些(愚蠢的)数据示例:
phrase,raw_phrase
delicious fruit mango, the mango is a delicious fruit
important object computer, the computer is an important object
popular banana fruit, banana is a popular fruit
pen important thing, pen is an important thing
purple grape, the grape is purple
phone world object, the phone is a worldwide object
请您参考如下方法:
您的过程 display_topics 不返回任何内容,但您将它的结果分配给变量 topics,然后将其设置为 Null。而且您不能遍历 Null 对象。
