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。
在這裏插入圖片描述

好啦,是不是很簡單,有問題可以私我

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章