前言

舆情分析、文本分析,在做特征提取时,需要把一整段内容合并后,提取内容中的热词、F-IDF权重和词频,本编以python编程,分享如何通过结巴分词简易上手。

代码讲解

先给代码片段配内容讲解,篇尾给完整的python代码。

1、读取文本信息

import pandas as pd# 1.导入数据语料的特征源数据#df_data = pd.read_table('data.txt', names=[ 'type', 'content'], encoding='utf-8')  #读txt文本的方式,names=[ 'type', 'content'] 表示读取两个字段内容df_data = pd.read_excel('data.xlsx',names=['type','content'],header =0)   contentslist = df_data.content.values.tolist()  #这是一个list,从多维数组df_data里面提取'content'这一列内容

引用pd,有两种读取方式,txt文件使用pd.read_table,excel文件使用pd.read_excel,内容如下:

txt文件的内容格式

excel文件的内容格式

2、通过结巴分词获取分词后的内容

import jieba
import jieba.analysedef jiebacut(content):content_S = []for line in content:# jieba分词 精确模式。返回一个列表类型,建议使用current_segment = jieba.lcut(line) #每一行都做分词if len(current_segment) > 1 and current_segment != '\r\n':content_S.append(current_segment)return content_S# 2、通过jieba分词,获取分词后的内容list
jieba_contentslist=jiebacut(contentslist)

3、获取删除停用词后的分词

import re
import jieba
import jieba.analyse# 删除内容中的停用词
def drop_stopwords(contents, stopwords):contents_clean = [] # 删除后的新闻all_words = []  # 构造词云所用的数据for line in contents:line_clean = []for word in line:if word in stopwords:  #这里只去掉停词表的内容,没有做去重continueif word == ' ' or bool(re.search(r'\d', word)):  #去掉空格和包含数字的分词(浮点型、带有%的百分比分词)continueline_clean.append(word)all_words.append(str(word))contents_clean.append(line_clean)return contents_clean, all_words# 3、读取停词内容stopwords = pd.read_csv('./stopwords.txt',index_col=False,sep='\t',quoting=3,names=['stopword'],encoding='utf-8')# 3.1、读取停用词内容stopwords = stopwords.stopword.values.tolist()# 3.2、得到删除停用词后的新闻以及词云数据#contents_clean是去掉停用词后的列表分词,all_words是去掉分词后的数组clean_content, all_words = drop_stopwords(jieba_contentslist, stopwords) #print(clean_content[0])

停用词文件stopwords.txt是一个一行一个词的文件,网上可以找到很多,分析出来的分词如果觉得没用,就加到停用词文件里面,另外停用词文件不支持过滤空格符,题主已经在代码中加入。

4、提取分词后内容的热词(包含TF-IDF权重)

import jieba
import jieba.analyse    # 4、把所有的内容累加成一条字符串,然后抽取主题# 4.1、把分词后的内容拼成一条字符串join_content_str=''for index_num in range(0,len(clean_content)):join_content_str += ''.join(clean_content[index_num]) #把分词粘在一行#print(join_content_str)# 4.2、通过结巴分词抽取主题#extract_tags函数参数说明:#第一个参数:待提取关键词的文本;#第二个参数:返回关键词的数量,重要性从高到低排序;#第三个参数:是否同时返回每个关键词的TF-IDF权重#第四个参数:词性过滤,为空表示不过滤,allowPOS=‘ns’, ‘n’, ‘vn’, ‘v’,提取地名、名词、动名词、动词keywords = jieba.analyse.extract_tags(join_content_str, topK=20, withWeight=True, allowPOS=())#for item in keywords:  #这个二维数组包含分词及对应的权重#    print(item[0], item[1])

5、绘制图云

#绘画词云
def showwordcloud(words_count,savefilename):from wordcloud import WordCloud # 词云库import matplotlib.pyplot as pltimport matplotlibmatplotlib.rcParams['figure.figsize'] = (10.0,5.0)wordcloud = WordCloud(font_path='./font/SIMLI.ttf',background_color='white',max_font_size=80)word_frequence = {x[0]:x[1] for x in words_count.head(100).values} # 这里最多显示词频前100的词汇,少于100个时,为实际的数量wordcloud = wordcloud.fit_words(word_frequence)plt.imshow(wordcloud)wordcloud.to_file(savefilename)  #保存为图片# 5、统计词频及绘画词云# 5.1、从所有词中抽取与keywords重合的词keywords_countlist=[]keywords_countdict={}for word in all_words:for ckword in wordlist:if word==ckword:keywords_countlist.append(ckword)if ckword in keywords_countdict:keywords_countdict[ckword]+=1else:keywords_countdict[ckword]=1breakdf_all_words = pd.DataFrame({'all_words':keywords_countlist})df_all_words.head()words_count=count_word(df_all_words)# 5.2、绘画词云showwordcloud(words_count,'IF-IDF词云.jpg')

keywords_countlist是存储抽取的热词,用来绘制图云;

keywords_countdict统计了热词的词频,用来保存到结果文件中。

图云函数模式是不显示中文的,但里面有一个引用格式文件的参数,font_path='./font/SIMLI.ttf',这个文件可以在win系统C:\Windows\Fonts目录下,找中文简体的格式文件,如下图所示

6、保存结果到文件

# 6保存到excel表中workbook = xlwt.Workbook(encoding = 'utf-8')worksheet = workbook.add_sheet(r'热词排行')worksheet.write(0,0, '热词')worksheet.write(0,1, 'IF-IDF特征值')worksheet.write(0,2, '词频')line=1for item in keywords:  #这个二维数组包含分词及对应的权重#print(item[0], item[1],keywords_countdict[item[0]])worksheet.write(line,0, item[0])worksheet.write(line,1, item[1])worksheet.write(line,2, keywords_countdict[item[0]])line+=1workbook.save('热词排行表.xls')

完整代码

# -*- coding: utf-8 -*-
"""
Created on Fri Jul  9 17:24:39 2019@author: 扶尔魔
"""
import re
import pandas as pd
import jieba
import jieba.analyse
import xlwtdef jiebacut(content):content_S = []for line in content:# jieba分词 精确模式。返回一个列表类型,建议使用current_segment = jieba.lcut(line) #每一行都做分词if len(current_segment) > 1 and current_segment != '\r\n':content_S.append(current_segment)return content_S# 删除内容中的停用词
def drop_stopwords(contents, stopwords):contents_clean = [] # 删除后的新闻all_words = []  # 构造词云所用的数据for line in contents:line_clean = []for word in line:if word in stopwords:  #这里只去掉停词表的内容,没有做去重continueif word == ' ' or bool(re.search(r'\d', word)):  #去掉空格和包含数字的分词(浮点型、带有%的百分比分词)continueline_clean.append(word)all_words.append(str(word))contents_clean.append(line_clean)return contents_clean, all_words#统计内容的词频,并排序
def count_word(df_all_words):#统计all_words每个词的词频,统计这个词频也是为了方便后面的词云展示import numpy# 分组统计words_count = df_all_words.groupby(by=['all_words'])['all_words'].agg({'count':numpy.size})# 根据count排序words_count = words_count.reset_index().sort_values(by=['count'],ascending=False)words_count.head()#print(words_count)return words_count#绘画词云
def showwordcloud(words_count,savefilename):from wordcloud import WordCloud # 词云库import matplotlib.pyplot as pltimport matplotlibmatplotlib.rcParams['figure.figsize'] = (10.0,5.0)wordcloud = WordCloud(font_path='./font/SIMLI.ttf',background_color='white',max_font_size=80)word_frequence = {x[0]:x[1] for x in words_count.head(100).values} # 这里只显示词频前100的词汇wordcloud = wordcloud.fit_words(word_frequence)plt.imshow(wordcloud)wordcloud.to_file(savefilename)  #保存为图片def hotwords():# 1.导入数据语料的特征源数据#df_data = pd.read_table('data.txt', names=[ 'type', 'content'], encoding='utf-8')  #读txt文本的方式df_data = pd.read_excel('data.xlsx',names=['type','content'],header =0)             #读excel文件方式contentslist = df_data.content.values.tolist()  #这是一个list,从多维数组df_data里面提取'content'这一列内容# 2、通过jieba分词,获取分词后的内容listjieba_contentslist=jiebacut(contentslist)# 3、读取停词内容stopwords = pd.read_csv('./stopwords.txt',index_col=False,sep='\t',quoting=3,names=['stopword'],encoding='utf-8')# 3.1、读取停用词内容stopwords = stopwords.stopword.values.tolist()# 3.2、得到删除停用词后的新闻以及词云数据#contents_clean是去掉停用词后的列表分词,all_words是去掉分词后的数组clean_content, all_words = drop_stopwords(jieba_contentslist, stopwords) #print(clean_content[0])# 4、把所有的内容累加成一条字符串,然后抽取主题# 4.1、把分词后的内容拼成一条字符串join_content_str=''for index_num in range(0,len(clean_content)):join_content_str += ''.join(clean_content[index_num]) #把分词粘在一行#print(join_content_str)# 4.2、通过结巴分词抽取主题#extract_tags函数参数说明:#第一个参数:待提取关键词的文本;#第二个参数:返回关键词的数量,重要性从高到低排序;#第三个参数:是否同时返回每个关键词的TF-IDF权重#第四个参数:词性过滤,为空表示不过滤,allowPOS=‘ns’, ‘n’, ‘vn’, ‘v’,提取地名、名词、动名词、动词keywords = jieba.analyse.extract_tags(join_content_str, topK=20, withWeight=True, allowPOS=())#for item in keywords:  #这个二维数组包含分词及对应的权重#    print(item[0], item[1])# 4.3、抽取关键字列wordlist = [x[0] for x in keywords]   # 获取第一列内容keywords_str = ' '.join(wordlist)print(keywords_str)# 5、统计词频及绘画词云# 5.1、从所有词中抽取与keywords重合的词keywords_countlist=[]keywords_countdict={}for word in all_words:for ckword in wordlist:if word==ckword:keywords_countlist.append(ckword)if ckword in keywords_countdict:keywords_countdict[ckword]+=1else:keywords_countdict[ckword]=1breakdf_all_words = pd.DataFrame({'all_words':keywords_countlist})df_all_words.head()words_count=count_word(df_all_words)# 5.2、绘画词云showwordcloud(words_count,'IF-IDF词云.jpg')# 6保存到excel表中workbook = xlwt.Workbook(encoding = 'utf-8')worksheet = workbook.add_sheet(r'热词排行')worksheet.write(0,0, '热词')worksheet.write(0,1, 'IF-IDF特征值')worksheet.write(0,2, '词频')line=1for item in keywords:  #这个二维数组包含分词及对应的权重#print(item[0], item[1],keywords_countdict[item[0]])worksheet.write(line,0, item[0])worksheet.write(line,1, item[1])worksheet.write(line,2, keywords_countdict[item[0]])line+=1workbook.save('热词排行表.xls')print('finish')if __name__=='__main__':hotwords()

片尾

如果有帮助,点个赞吧,博主近期会分享一些文本分析相关的文章,感兴趣的可以点个关注。

上手结巴分词文本分析,输出热词、TF-IDF权重和词频相关推荐

  1. Python:文本分析必备—搜狗词库

    全文阅读:Python:文本分析必备-搜狗词库| 连享会主页 目录 1. 引言 2. 词典的妙用 3. 搜狗词库的下载 3.1 抓取12个页面链接 3.2 爬取所有词库名称和下载链接 3.3 下载细胞 ...

  2. hmm 求隐藏序列_结巴分词3--基于汉字成词能力的HMM模型识别未登录词

    1 算法简介 在结巴分词2--基于前缀词典及动态规划实现分词 博文中,博主已经介绍了基于前缀词典和动态规划方法实现分词,但是如果没有前缀词典或者有些词不在前缀词典中,jieba分词一样可以分词,那么j ...

  3. jieba结巴分词--关键词抽取(核心词抽取)

    转自:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 1 简介 关键词抽取就是从文本里面把跟这篇文档意义最相关的一些词抽取出来.这个可以追溯到文献 ...

  4. 十分钟快速上手结巴分词

    一.特点 1.支持三种分词模式 精确模式,试图将句子最精确的切开: 全模式,把句子中所有的可以成词的词语都扫描出来,速度非常快,但是不能解决歧义: 搜索引擎模式,在精确模式的基础上,对长词再次切分,提 ...

  5. ik与拼音分词器,拓展热词/停止词库

    说明:本篇文章讲述elasticsearch分词器插件的安装,热词库停止词库的拓展,文章后面提到elasticsearch ,都是以es简称. 以下分词器的安装以ik分词器和pinyin分词器为例说明 ...

  6. ik分词器的热词更新_ik与拼音分词器,拓展热词/停止词库

    说明:本篇文章讲述elasticsearch分词器插件的安装,热词库停止词库的拓展,文章后面提到elasticsearch ,都是以es简称. 以下分词器的安装以ik分词器和pinyin分词器为例说明 ...

  7. 自然语言处理︱简述四大类文本分析中的“词向量”(文本词特征提取)

    笔者在看各种NLP的论文.文献.博客之中发现在应用过程中,有种类繁多的词向量的表达.笔者举例所看到的词向量有哪些. 词向量一般被看做是文档的特征,不同词向量有不同的用法,本文介绍了四类词向量: Has ...

  8. jieba 词典 词频_python jieba分词(添加停用词,用户字典 取词频

    1 http2 回复3 !4 "5 #6 $7 % 8 & 9 '10 (11 )12 * 13 + 14 ,15 - 16 -- 17 .18 ..19 ...20 ......2 ...

  9. 使用lingpipe自然语言处理包进行文本分类/** * 使用 lingpipe的tf/idf分类器训练语料 * * @author laigood */ public class trai

    /**  * 使用 lingpipe的tf/idf分类器训练语料  *   * @author laigood  */ public class traintclassifier { //训练语料文件 ...

最新文章

  1. cisco与h3c的console、vty配置比较
  2. 结构体内字节手动对齐(#pragam pack)
  3. [转]string.Formate 格式化用法
  4. lseek函数的使用
  5. 数据挖掘—朴素贝叶斯分类算法(Java实现)
  6. js 简单弹框toast
  7. 语音识别,搜狗的下一个大梦想?
  8. 查看各浏览器各版本的兼容情况
  9. php日志在哪,php日志在哪
  10. HTML期末学生大作业-视频影视网页html+css+javascript(带报告册)
  11. SSM | Spring
  12. Nginx正则表达式locationrewrite
  13. Android ListView异步获取网络图片
  14. 计算机组成1046Q表示什么,计算器里的tanh是什么意思
  15. 为什么蓝牙电子产品要做BQB认证
  16. 用AI生成假员工,8天众筹3万美元,这家创业公司2/3的成员都是假的!
  17. python禅语_42:对象、类、以及从属关系
  18. 20个必不可少的Python库也是基本的第三方库
  19. 海尔微型计算机U盘启动,海尔台式电脑如何设置u盘启动_海尔台式电脑bios设置u盘启动教程...
  20. Mysql常见面试题(进阶知识点)

热门文章

  1. 青蛙变态跳+python
  2. 仓储系统 wms 数据中心 数据员操作指南 第四节 预拨单准备 配货员安排 第二部分 出货信息表 格式设置
  3. python数据处理——堆积面积图
  4. 面试题:大公司面试题 !=!=未看
  5. C语言笔记之个税计算
  6. 反垃圾邮件产品等级划分
  7. Android聊天软件的开发(四)--通讯录
  8. 9000字通俗易懂的讲解下Java注解,你还看不明白?
  9. rime切换全角标点和半角标点
  10. 【Python】一键抠图,3行代码实现照片/证件照换背景色