LDA中文文本挖掘代码分享

原代码并非我原创,但我在自己的电脑上不断报错,所以加以修改补充后分享给大家,自己运行中需要注意的问题:

1、文本数据保存的时候记得要选择utf-8否则会报错

2、中文停词表自己去网上找就OK啦,网上有很多

3、可以选择读单个文件or文件夹的所有文件,默认的是单个文件,如果要用所有文件,把注释那部分删掉#就可以了

文件夹文件读取
#print('读取文件并获取内容...')
#all_content = []  # 总列表,用于存储所有文件的文本内容
#for root, dirs, files in os.walk('../清洗过'):  # 分别读取遍历目录下的根目录、子目录和文件列表
  for file in files:  # 读取每个文件
       file_name = os.path.join(root, file)  # 将目录路径与文件名合并为带有完整路径的文件名
       with open(file_name, encoding='utf-8') as f:  # 以只读方式打开文件
           data = f.read()  # 读取文件内容
           words = jieba.cut(data)
       all_content.extend(words)  # 从文件内容中获取文本并将结果追加到总列表

读取单个文件
with open('/Users/Desktop/上课/文献/LDA/标题.txt', encoding='utf-8') as f:
打开新的文本,记得改成你文件的路径
     data = f.read()  # 读取文本数据
text = data
words = jieba.cut(text)
jieba.suggest_freq('液压支架', True)
#遇到固定名词但系统却给拆分了,可以用这个,不需要的话删掉就可以了

4、记得改路径

以下是全文

导入库
import os
import jieba  # 分词模块
from gensim import corpora, models  # gensim的词频统计和主题建模模块

构建停词库
def get_custom_stopwords(stop_words_file):
    with open(stop_words_file, encoding='UTF-8') as f:
        stopwords = f.read()
    stopwords_list = stopwords.split('\n')
    custom_stopwords_list = [i for i in stopwords_list]
    return custom_stopwords_list

文件夹文件读取
#print('读取文件并获取内容...')
#all_content = []  # 总列表,用于存储所有文件的文本内容
#for root, dirs, files in os.walk('../清洗过'):  # 分别读取遍历目录下的根目录、子目录和文件列表
  for file in files:  # 读取每个文件
       file_name = os.path.join(root, file)  # 将目录路径与文件名合并为带有完整路径的文件名
       with open(file_name, encoding='utf-8') as f:  # 以只读方式打开文件
           data = f.read()  # 读取文件内容
           words = jieba.cut(data)
       all_content.extend(words)  # 从文件内容中获取文本并将结果追加到总列表

读取单个文件
with open('/Users/yiban/Desktop/上课/文献/LDA/标题.txt', encoding='utf-8') as f:  # 打开新的文本
     data = f.read()  # 读取文本数据
text = data
words = jieba.cut(text)
jieba.suggest_freq('液压支架', True)

去停词
stop_words_file = "/Users/yiban/Desktop/上课/文献/LDA/中文停词表.txt"
stopwords = get_custom_stopwords(stop_words_file)
words_ls = [i for i in words if i not in stopwords] # 将不在去除词列表中的词添加到列表中
words_ls = list(set(words).difference(set(stopwords)))

for x in words_ls:
    print(x)

构造词典:分词列表转字典
dictionary = corpora.Dictionary([words_ls])
print('{:*^60}'.format('token和word mapping预览:'))
for i, w in list(dictionary.items())[:5]:  # 循环读出字典前5条的每个key和value,对应的是索引值和分词
    print('token:%s -- word:%s' % (i, w))

生成语料库
corpus = [dictionary.doc2bow([words]) for words in words_ls]
print('{:*^60}'.format('bag of words review:'))# 打印输出第一条语料库
print(corpus[0])

设置主题的个数
lda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=3)

打印所有主题,每个主题显示5个词
for topic in lda.print_topics(num_words=5):
    print(topic)

主题推断
print('{:*^60}'.format('主题推断'))
print(lda.inference(corpus))

Original: https://blog.csdn.net/zxcvbygll/article/details/121928978
Author: zxcvbygll
Title: LDA中文文本挖掘代码分享

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/530963/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球