如何仅在gensim中访问主题词

Muh*_*akh 8 python nlp lda gensim topic-modeling

我使用 Gensim 构建了 LDA 模型,我只想获取主题词如何仅获取主题词没有概率也没有 IDs.words

我在 gensim 中尝试了 print_topics() 和 show_topics() 函数,但我找不到干净的词!

这是我使用的代码

dictionary = corpora.Dictionary(doc_clean)
doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]
Lda = gensim.models.ldamodel.LdaModel
ldamodel = Lda(doc_term_matrix, num_topics=12, id2word = dictionary, passes = 100, alpha='auto', update_every=5)
x = ldamodel.print_topics(num_topics=12, num_words=5)
for i in x:
    print(i[1])
    #print('\n' + str(i))

0.045*???? + 0.045*??????? + 0.045*??????? + 0.045*?????? + 0.045*?????
0.021*??? + 0.021*??????????? + 0.021*???? + 0.021*???? + 0.021*???????
0.068*???????? + 0.068*???????? + 0.068*????????? + 0.068*????? + 0.005*????
0.033*????? + 0.033*???????? + 0.033*??????? + 0.033*????? + 0.033*?
0.007*?????? + 0.007*????? + 0.007*????? + 0.007*????? + 0.007*????
0.116*???? + 0.116*??????? + 0.060*???? + 0.060*??? + 0.005*?????
0.064*??? + 0.064*??? + 0.064*????? + 0.064*????????? + 0.064*???????????
0.036*?????? + 0.036*??????? + 0.036*?? + 0.036*??????? + 0.036*???????
0.052*?????? + 0.052*?? + 0.052*???? + 0.052*?????? + 0.052*?????
0.034*???????? + 0.034*?????? + 0.034*?? + 0.034*????? + 0.034*????
0.035*?? + 0.035*??????? + 0.035*??????? + 0.035*??????? + 0.035*???????
0.064*????? + 0.064*????? + 0.064*?? + 0.064*????? + 0.064*???
Run Code Online (Sandbox Code Playgroud)

我试过 show_topics 并给出了相同的输出

y = np.array(ldamodel.show_topics(num_topics=12, num_words=5))
for i in y[:,1]:
    #if i != '%d':
    #print([str(word) for word in i])
    print(i)
Run Code Online (Sandbox Code Playgroud)

如果我有主题 ID,我如何访问它的单词和其他信息

提前致谢

old*_*onk 6

我认为下面的代码片段应该为您提供一个包含每个主题(tp)和该主题中相应单词列表(wd)的元组列表

x=ldamodel.show_topics(num_topics=12, num_words=5,formatted=False)
topics_words = [(tp[0], [wd[0] for wd in tp[1]]) for tp in x]

#Below Code Prints Topics and Words
for topic,words in topics_words:
    print(str(topic)+ "::"+ str(words))
print()

#Below Code Prints Only Words 
for topic,words in topics_words:
    print(" ".join(words))
Run Code Online (Sandbox Code Playgroud)


小智 5

另一个答案是给出一个字符串,其中包含与每个单词相关的权重。但是如果您想单独获取主题中的每个单词以进行进一步的工作。那么你可以试试这个。这里主题号是字典的键,值是一个字符串,包含该主题中以空格分隔的所有单词

x=ldamodel.show_topics()

twords={}
for topic,word in x:
    twords[topic]=re.sub('[^A-Za-z ]+', '', word)
print(twords)
Run Code Online (Sandbox Code Playgroud)