【发布时间】:2023-03-10 20:09:01
【问题描述】:
我对在 Python 中执行 LDA 感到有些困惑。 我有一个文档文件,我想运行 LDA 并获取主题。
import docx
import nltk
import gensim
from gensim.models import hdpmodel, ldamodel
from gensim import corpora
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
fullText=getText('ElizabethII.docx')
#create lda object
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in fullText]
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word)
== 1)
texts = [[word for word in text if word not in tokens_once]
for text in texts]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
lda = ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=5, passes=15)
topics = lda.show_topics(num_words=4)
for topic in topics:
print(topic)
corpus_lda = lda[corpus]
print(lda.show_topics())
结果我得到了这个:
(0, '0.723*"r" + 0.211*"f" + 0.025*"5" + 0.013*"-"')
(1, '0.410*"e" + 0.258*"t" + 0.206*"h" + 0.068*"m"')
(2, '0.319*"n" + 0.162*"l" + 0.113*"c" + 0.101*"u"')
(3, '0.503*"i" + 0.324*"d" + 0.113*"b" + 0.041*"9"')
(4, '0.355*"o" + 0.307*"s" + 0.106*"w" + 0.052*"v"')
这让我很困惑。为什么我得到字符而不是主题?是因为我的 docx 文件(包含 1900 个单词?)还是代码错误?或者我应该为句子(段落)提供主题? (怎么做?)
【问题讨论】:
标签: python nltk lda topic-modeling