Python中文文本分词、词频统计、词云绘制

本文主要从中文文本分词、词频统计、词云绘制方面介绍Python中文文本分词的使用。会使用到的中文文本处理包包括:wordcloud,jieba,re(正则表达式),collections。

1 准备工作

导入相关的包,读取相关数据。

#导入包
import pandas as pd                      #数据处理包
import numpy as np                       #数据处理包
from wordcloud import WordCloud          #绘制词云
import jieba                             #中文分词包
import jieba.posseg as pseg
import re                                #正则表达式,可用于匹配中文文本
import collections                       #计算词频
#读取数据,使用pandas读取csv
df_question = pd.read_csv("D:/data/raw_data_20200401_copy/question.csv",low_memory=False)
#选择问题描述部分
df_description = df_question["description"].drop_duplicates().reset_index() #去除重复问题
list_description = df_description["description"].tolist() 
description_all = "start"
for i in range(999): #选定一定范围作为示范,全部处理实在太多了
    description_all = description_all+list_description[i]
#选取中文:使用正则表达式
filter_pattern = re.compile('[^\u4E00-\u9FD5]+')
chinese_only = filter_pattern.sub('', description_all)

2 中文分词

#中文分词
words_list = pseg.cut(chinese_only)  

#删除停用词
stopwords1 = [line.rstrip() for line in open('D:/data/BI/stop_words/中文停用词库.txt', 'r', encoding='utf-8')]
stopwords2 = [line.rstrip() for line in open('D:/data/BI/stop_words/哈工大停用词表.txt', 'r', encoding='utf-8')]
stopwords3 = [line.rstrip() for line in open('D:/data/BI/stop_words/四川大学机器智能实验室停用词库.txt', 'r',encoding='utf-8')]
stopwords = stopwords1 + stopwords2 + stopwords3

meaninful_words = []
for word, flag in words_list:
    if word not in stopwords:
        meaninful_words.append(word)

3 计算词频

绘制词频并查看词频排在前30的词。

#计算词频,一行解决
word_counts = collections.Counter(meaninful_words) # 对分词做词频统计
word_counts_top30 = word_counts.most_common(30) # 获取前30最高频的词
print (word_counts_top30) 

4 绘制词云

#绘制词云
wc = WordCloud(background_color = "black",max_words = 300,font_path='C:/Windows/Fonts/simkai.ttf',min_font_size = 15,max_font_size = 50,width = 600,height = 600)
wc.generate_from_frequencies(word_counts)
wc.to_file("wordcoud.png")

看一下结果,因为数据来源于某医患交互平台,分析的是患者关注的问题都有哪些,所以结果如下图。可以看到大家在关注什么问题,一般哪些问题在线上被问到的比较多。。。可能数据不全,仅做示范hhh。
Python中文文本分词、词频统计、词云绘制_第1张图片

好啦,是不是很简单,有问题可以私我

你可能感兴趣的:(python,文本分析,python,数据挖掘)