2016-07-22 21 views
0

我正在做一些主题建模,并期待存储我的分析结果。将生成器表达式(<genexpr>)转换为列表?

import pandas as pd, numpy as np, scipy 
import sklearn.feature_extraction.text as text 
from sklearn import decomposition 

descs = ["You should not go there", "We may go home later", "Why should we do your chores", "What should we do"] 

vectorizer = text.CountVectorizer() 

dtm = vectorizer.fit_transform(descs).toarray() 

vocab = np.array(vectorizer.get_feature_names()) 

nmf = decomposition.NMF(3, random_state = 1) 

topic = nmf.fit_transform(dtm) 

topic_words = [] 

for t in nmf.components_: 
    word_idx = np.argsort(t)[::-1][:20] 
    topic_words.append(vocab[i] for i in word_idx) 

for t in range(len(topic_words)): 
    print("Topic {}: {}\n".format(t, " ".join([word for word in topic_words[t]]))) 

打印:

Topic 0: do we should your why chores what you there not may later home go 

Topic 1: should you there not go what do we your why may later home chores 

Topic 2: we may later home go what do should your you why there not chores 

我想写这些主题的文件,所以我想将它们存储在一个列表可能会奏效,像这样:

l = [] 
for t in range(len(topic_words)): 
    l.append([word for word in topic_words[t]]) 
    print("Topic {}: {}\n".format(t, " ".join([word for word in topic_words[t]]))) 

l只是最后一个空的数组。我如何将这些单词存储在列表中?

+0

'[在topic_words一个字一个字[T]] = = list(topic_words [t])' –

+0

题外话题:不要使用'l'作为变量名,它看起来太像数字'1'。 –

回答

3

您正在将生成器表达式附加到列表topic_words,因此第一次打印时,生成器表达式已经用尽。你可以做,而不是:

topic_words = [] 

for t in nmf.components_: 
    word_idx = np.argsort(t)[::-1][:20] 
    topic_words.append([vocab[i] for i in word_idx]) 
#     ^      ^

有了这个,你显然不会需要一个新的列表,你可以打印出:

for t, words in enumerate(topic_words, 1): 
    print("Topic {}: {}\n".format(t, " ".join(words))) 
相关问题