LDA模型的实现【附完整代码】

Python实现LDA模型 附完整代码

    • Python 实现LDA模型

Python 实现LDA模型



# -*- coding: utf-8 -*-

"""
Created on Mon May 13 22:05:05 2019
@author: PC
"""
# -*- coding: utf-8 -*-
import csv
from gensim import corpora, models
import gensim #从原始的非结构化的文本中,无监督地学习到文本隐层的主题向量表达。;它支持包括TF-IDF,LSA,LDA,和word2vec在内的多种主题模型算法, 
import jieba #“结巴”中文分词:Python 中文分词组件
import re #Python的标准库,主要用于字符串匹配。

def load_csv_text(file_name):#定义一个读取文件函数
   csv_data_list = []
   path = 'G:\论文2.0\情感\LDA\\'+ file_name#此处改为你的文件路径即可
   file = open(path,'r',encoding="utf-8")#打开文件
   file.readline()#读取文件;以行为单位返回字符串,也就是每次读一行,依次循环
   csv_reader = csv.reader(file)#reader返回的值是csv文件中每行的列表,将每行读取的值作为列表返回
   for one_row in csv_reader:
       csv_data_list.append(one_row)#将传入的对象附加(添加)到csv_data_list列表中。
   return csv_data_list#返回csv_data_list列表。
   
 def word_get(text):#定义一个获取词语的函数
   word_list = [] #创建一个空列表
   words = jieba.lcut(text)#精确分词,将text中的每个词分离出来
   for word in words:#读取每一个词
       word_list.append(word)#将每个词添加到word_list中
   return word_list
   
def stopwordslist(filepath):#定义一个停止词函数;忽略掉一些高频率、无意义的词
   stopwords = [line.strip() for line in open(filepath, 'r').readlines()]#对每一行的去除首尾空格,然后储存到line列表中。
   return stopwords
   
stop_words = stopwordslist('G:\论文2.0\情感\LDA\\stop_word.csv')#调用停止词函数

hi = 1
while hi <= 1:#有多少个文件就填多少
   hstr = str(hi)
   file_name = hstr + '.csv'#要读取的文件名称,此处将大量文件设置为1.csv 2.csv 便于批量处理
   csv_data_list = load_csv_text(file_name)#调用函数读取文件
   text=''
    #正则表达式 +:匹配1到任意多个任意字符 [\d]:匹配任意阿拉伯数字,加入字符组
   for i in range(len(csv_data_list)): #遍历csv_data_list列表
      csv_text = str(csv_data_list[i][0])#返回一个对象的string格式;适合人阅读的格式
      csv_text = re.sub(r'([\d]+)','',csv_text).lower()#将csv_text中的所有数字替换掉;并将大写字母转换为小写字母
      csv_text = re.sub("[A-Za-z0-9\!\%\[\]\,\。\...+\..\.+\_+\##]","", csv_text)#替换掉字母和符号
      csv_text = re.sub("\u200b","", csv_text)#替换掉不可见字符\u200b  
      csv_text=word_get(csv_text)
      
      for i in range(len(csv_text)):
          word=csv_text[i]
          if word not in stop_words:#如果这个词不是停止词。
               if word != '\t':#如果词语不是制表符
                   text = text + word.strip()

   texts=[]
   word_list= word_get(text)#将text中的词语精确分词
   for i in range(len(word_list)):
   
     text= [word_list[i]]
     texts.append(text)#将分词后的text存为列表
   hi = hi + 1
   print(hstr + 'over')  
  
#LDA模型
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(doc) for doc in texts ]

lda =gensim.models.ldamodel.LdaModel(corpus,num_topics=5, id2word = dictionary,passes=2)#调用LDA模型,请求潜在主题数3;训练语料库2次

#lda.print_topic(10, topn=5)

print(lda.print_topics(num_topics=5,num_words=5))#打印主题,5个主题,7个单词

 
def text_save(content,filename,mode='a'):
    #Try to save a list variable in txt file
   file = open(filename,mode)
   for i in range(len(content)):
       file.write(str(content[i])+'\n')
   file.close()

你可能感兴趣的:(Python,LDA,新手,完整代码)