对不起,我还是解决不了这个问题。我正在使用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发布于 2018-09-17 10:50:33
正如错误消息所指出的,您的错误发生在以下一行:
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 ""发布于 2018-09-17 10:42:47
过程display_topics不返回任何内容,但是将其结果赋值给变量topics,然后将变量设置为Null。而且您不能在Null对象上迭代。
https://stackoverflow.com/questions/52365561
复制相似问题