主题建模代码

1.单个文本的主题建模
import jieba
from gensim import corpora, models
import pyLDAvis.gensim

# 读取文本文件
with open('topic1.txt', 'r', encoding='utf-8') as file:
    text = file.read()

# 分词
seg_list = jieba.cut(text)
tokens = [token for token in seg_list if len(token) > 1]

# 创建语料库
dictionary = corpora.Dictionary([tokens])
corpus = [dictionary.doc2bow(tokens)]

# 构建LDA模型
lda_model = models.LdaModel(corpus, num_topics=5, id2word=dictionary)

# 准备数据并生成可视化对象
data = pyLDAvis.gensim.prepare(lda_model, corpus, dictionary)

# 保存可视化结果为HTML文件
pyLDAvis.save_html(data, 'visualization1.html')

2.多个文本的主题建模

import jieba
from gensim import corpora, models
import pyLDAvis.gensim

# 读取多个文本文件
file_paths = ['1-1-1.txt', '1-1-2.txt', '1-1-3.txt']  # 假设有三个文本文件
texts = []
for file_path in file_paths:
    with open(file_path, 'r', encoding='utf-8') as file:
        text = file.read()
        texts.append(text)

# 分词
tokenized_texts = []
for text in texts:
    seg_list = jieba.cut(text)
    tokens = [token for token in seg_list if len(token) > 1]
    tokenized_texts.append(tokens)

# 创建语料库
dictionary = corpora.Dictionary(tokenized_texts)
corpus = [dictionary.doc2bow(tokens) for tokens in tokenized_texts]

# 构建LDA模型
lda_model = models.LdaModel(corpus, num_topics=5, id2word=dictionary)

# 准备数据并生成可视化对象
data = pyLDAvis.gensim.prepare(lda_model, corpus, dictionary)

# 显示可视化结果
pyLDAvis.save_html(data, 'visualization1-2-3.html')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值