• 初试主题模型LDA-基于python的gensim包


    http://blog.csdn.net/a_step_further/article/details/51176959

    LDA是文本挖掘中常用的主题模型,用来从大量文档中提取出最能表达各个主题的一些关键词,具体算法原理可参阅KM上相关文章。笔者因业务需求,需对腾讯微博上若干账号的消息进行主题提取,故而尝试了一下该算法,基于python的gensim包实现一个简单的分析。

    准备工作

    • 安装python的中文分词模块, jieba
    • 安装python的文本主题建模的模块, gensim (官网 https://radimrehurek.com/gensim/)。 这个模块安装时依赖了一大堆其它包,需要耐心地一个一个安装。
    • 到网络上下载中文停用词表

    上代码

    [python]
      1. #!/usr/bin/python  
      2. #coding:utf-8  
      3. import sys  
      4. reload(sys)  
      5. sys.setdefaultencoding("utf8")  
      6. import jieba  
      7. from gensim import corpora, models  
      8.   
      9.   
      10. def get_stop_words_set(file_name):  
      11.     with open(file_name,'r') as file:  
      12.         return set([line.strip() for line in file])  
      13.   
      14. def get_words_list(file_name,stop_word_file):  
      15.     stop_words_set = get_stop_words_set(stop_word_file)  
      16.     print "共计导入 %d 个停用词" % len(stop_words_set)  
      17.     word_list = []  
      18.     with open(file_name,'r') as file:  
      19.         for line in file:  
      20.             tmp_list = list(jieba.cut(line.strip(),cut_all=False))  
      21.             word_list.append([term for term in tmp_list if str(term) not in stop_words_set]) #注意这里term是unicode类型,如果不转成str,判断会为假  
      22.     return word_list  
      23.   
      24.   
      25. if __name__ == '__main__':  
      26.     if len(sys.argv) < 3:  
      27.         print "Usage: %s <raw_msg_file> <stop_word_file>" % sys.argv[0]  
      28.         sys.exit(1)  
      29.   
      30.     raw_msg_file = sys.argv[1]  
      31.     stop_word_file = sys.argv[2]  
      32.     word_list = get_words_list(raw_msg_file,stop_word_file) #列表,其中每个元素也是一个列表,即每行文字分词后形成的词语列表  
      33.     word_dict = corpora.Dictionary(word_list)  #生成文档的词典,每个词与一个整型索引值对应  
      34.     corpus_list = [word_dict.doc2bow(text) for text in word_list] #词频统计,转化成空间向量格式  
      35.     lda = models.ldamodel.LdaModel(corpus=corpus_list,id2word=word_dict,num_topics=10,alpha='auto')  
      36.   
      37.     output_file = './lda_output.txt'  
      38.     with open(output_file,'w') as f:  
      39.         for pattern in lda.show_topics():  
      40.             print >> f, "%s" % str(pattern) 

    另外还有一些学习资料:https://yq.aliyun.com/articles/26029 [python] LDA处理文档主题分布代码入门笔记

  • 相关阅读:
    面试问烂的 MySQL 四种隔离级别,看完吊打面试官!
    注解Annotation实现原理与自定义注解例子
    趣图:苦逼的后端工程师
    session深入探讨
    趣图:听说996工作可以获得巨大成长
    面试官:一个 TCP 连接可以发多少个 HTTP 请求?
    聊聊前后端分离接口规范
    趣图:什么?需求文档又改了
    ASP.NET页面中去除VIEWSTATE视
    C#
  • 原文地址:https://www.cnblogs.com/flippedkiki/p/7131267.html
Copyright © 2020-2023  润新知