Python,LDA:如何使用Gensim获取关键字的id而不是关键字本身?

时间:2017-01-20 14:28:54

标签: python gensim lda

我正在使用Gensim应用LDA方法从文档中提取关键字。 我可以提取主题,然后分配这些主题和与文档关联的关键词。

我想要这些术语(或关键词)的ID而不是术语本身。我知道corpus[i]提取了文档i的一对夫妇[(term_id,term_frequency)...]的列表,但我看不出如何在我的代码中使用它来仅提取ID和将它分配给我的结果。

我的代码如下:

ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=passes, minimum_probability=0)

# Assinging the topics to the document in corpus
lda_corpus = ldamodel[corpus]

# Find the threshold, let's set the threshold to be 1/#clusters,
# To prove that the threshold is sane, we average the sum of all probabilities:
scores = list(chain(*[[score for topic_id,score in topic] \
                     for topic in [doc for doc in lda_corpus]]))

threshold = sum(scores)/len(scores)
print(threshold)

for t in range(len(topic_tuple)):  

    key_words.append([topic_tuple[t][j][0] for j in range(num_words)])
    df_key_words = pd.DataFrame({'key_words' : key_words})

    documents_corpus.append([j for i,j in zip(lda_corpus,doc_set) if i[t][1] > threshold])
    df_documents_corpus = pd.DataFrame({'documents_corpus' : documents_corpus})

    documents_corpus_id.append([i for d,i in zip(lda_corpus, doc_set_id) if d[t][1] > threshold])
    df_documents_corpus_id = pd.DataFrame({'documents_corpus_id' : documents_corpus_id})


result.append(pd.concat([df_key_words, df_documents_corpus, df_documents_corpus_id ], axis=1))

提前感谢您,并询问我是否需要更多信息。

1 个答案:

答案 0 :(得分:0)

如果有人遇到与我相同的问题,以下是反向地图的答案:

reverse_map = dict((ldamodel.id2word[id],id) for id in ldamodel.id2word)

感谢bigdeeperadvisors