对不起,我仍然无法解决这个无问题。我正在使用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)
我试图放一个条件忽略名称,但它不起作用。我仍然有同样的错误。
主题0:
订单取消交货日期不希望商店总是提前
主题1:
产品不破仅包到货收到的颜色交付
主题2:
产品不提前退回网站商店收据订单
没有
主题文件
回溯(最近一次调用最后一次):文件“NMF.py”,第49行,用于范围内的主题(len(主题)):
TypeError:'NoneType'类型的对象没有len()
我需要这个结果:
主题0:
订单取消交货日期不希望商店总是提前
主题1:
产品不破仅包到货收到的颜色交付
主题2:
产品不提前退回网站商店收据订单
主题文件
主题0:
文字文字
文字文字
文字文字
主题1:
文字文字
文字文字
文字文字
主题2:
文字文字
文字文字
文字文字
一些(愚蠢的)数据例如:
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
正如错误消息所指出的,您的错误发生在以下行中:
for topic in range(len(topics)):
因为python试图得到对象topics
的长度,作为None
类型它没有长度。
如果你想在topics
是Null
时跳过整个循环你可以使用:
for topic in topics:
并将所有topics[topic]
改为topic
或者,如果您想捕获该错误,您可以写:
try:
l = len(topics)
except TypeError:
# do somthing about it like:
l = 0
for topic in range(l):
# go on in topic loop
或者,您可以在创建topics
对象后检查None,其中:
if variable is None:
topics = #something else or empty with ""
您的程序display_topics
不会返回任何内容,但您将其结果分配给变量topics
,然后将其设置为Null
。而你不能迭代Null
对象。