Python統(tǒng)計(jì)詞頻并繪制圖片(附完整代碼)
效果



1 實(shí)現(xiàn)代碼
讀取txt文件:
def readText(text_file_path):
with open(text_file_path, encoding='gbk') as f: #
content = f.read()
return content
得到文章的詞頻:
def getRecommondArticleKeyword(text_content, key_word_need_num = 10, custom_words = [], stop_words =[], query_pattern = 'searchEngine'):
'''
:param text_content: 文本字符串
:param key_word_need_num: 需要的關(guān)鍵詞數(shù)量
:param custom_words: 自定義關(guān)鍵詞
:param stop_words: 不查詢關(guān)鍵詞
:param query_pattern:
precision:精確模式————試圖將句子最精確地切開(kāi),適合文本分析;
entire:全模式————把句子中所有的可以成詞的詞語(yǔ)都掃描出來(lái), 速度非???,但是不能解決歧義;
searchEngine:搜索引擎模式————在精確模式的基礎(chǔ)上,對(duì)長(zhǎng)詞再次切分,提高召回率,適合用于搜索引擎分詞;
paddle模式————利用PaddlePaddle深度學(xué)習(xí)框架,訓(xùn)練序列標(biāo)注(雙向GRU)網(wǎng)絡(luò)模型實(shí)現(xiàn)分詞。同時(shí)支持詞性標(biāo)注。
:return:
'''
# jieba.enable_paddle()
# paddle.fluid.install_check.run_check()
if not isinstance(text_content, str):
raise ValueError('文本字符串類型錯(cuò)誤!')
if not isinstance(key_word_need_num, int):
raise ValueError('關(guān)鍵詞個(gè)數(shù)類型錯(cuò)誤!')
if not isinstance(custom_words, list):
raise ValueError('自定義關(guān)鍵詞類型錯(cuò)誤!')
if not isinstance(stop_words, list):
raise ValueError('屏蔽關(guān)鍵詞類型錯(cuò)誤!')
if not isinstance(query_pattern, str):
raise ValueError('查詢模式類型錯(cuò)誤!')
# 添加自定義關(guān)鍵詞
for word in custom_words:
jieba.add_word(word)
if query_pattern == 'searchEngine':
key_words = jieba.cut_for_search(text_content)
elif query_pattern == 'entire':
key_words = jieba.cut(text_content, cut_all=True, use_paddle=True)
elif query_pattern == 'precision':
key_words = jieba.cut(text_content, cut_all=False, use_paddle=True)
else:
return []
# print("拆分后的詞: %s" % " ".join(key_words))
# 過(guò)濾后的關(guān)鍵詞
stop_words = set(stop_words)
word_count = Counter()
for word in key_words:
if len(word) > 1 and word not in stop_words:
word_count[word] += 1
# res_words = list()
# for data in word_count.most_common(key_word_need_num):
# res_words.append(data[0])
# return res_words
return word_count
繪制圖片:
def drawWordsCloud(word_count, save_img_filePath='', img_mask_filePath=''):
# print(word_count)
# print(type(word_count))
if len(img_mask_filePath) != 0:
img_mask = np.array(Image.open(img_mask_filePath)) #打開(kāi)遮罩圖片,將圖片轉(zhuǎn)換為數(shù)組
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫(kù)”,不支持中文
background_color="white", # 設(shè)置背景顏色
max_words=200, # 設(shè)置最大顯示的字?jǐn)?shù)
max_font_size=50, # 設(shè)置字體最大值
random_state=30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案
width=400,
height=200,
mask=img_mask
)
else:
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫(kù)”,不支持中文
background_color="white", # 設(shè)置背景顏色
max_words=200, # 設(shè)置最大顯示的字?jǐn)?shù)
max_font_size=50, # 設(shè)置字體最大值
random_state=30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案
width=400,
height=200
)
# 繪圖
wc.generate_from_frequencies(word_count) #從字典生成詞云
plt.imshow(wc) #顯示詞云
plt.axis('off') #關(guān)閉坐標(biāo)軸
plt.show() #顯示圖像
# 保存圖片
if len(save_img_filePath) != 0:
wc.to_file(save_img_filePath)
else:
pass
2 完整代碼
#-*- coding : utf-8-*-
import jieba
from collections import Counter
import paddle
import wordcloud #詞云展示庫(kù)
import matplotlib.pyplot as plt #圖像展示庫(kù)
import time
from PIL import Image
import numpy as np
def timer(func):
def calculateTime(*args, **kwargs):
t = time.perf_counter()
result = func(*args, **kwargs)
print(f'func {func.__name__} coast time:{time.perf_counter() - t:.8f} s')
return result
return calculateTime
def readText(text_file_path):
with open(text_file_path, encoding='gbk') as f: #
content = f.read()
return content
@timer
def getRecommondArticleKeyword(text_content, key_word_need_num = 10, custom_words = [], stop_words =[], query_pattern = 'searchEngine'):
'''
:param text_content: 文本字符串
:param key_word_need_num: 需要的關(guān)鍵詞數(shù)量
:param custom_words: 自定義關(guān)鍵詞
:param stop_words: 不查詢關(guān)鍵詞
:param query_pattern:
precision:精確模式————試圖將句子最精確地切開(kāi),適合文本分析;
entire:全模式————把句子中所有的可以成詞的詞語(yǔ)都掃描出來(lái), 速度非常快,但是不能解決歧義;
searchEngine:搜索引擎模式————在精確模式的基礎(chǔ)上,對(duì)長(zhǎng)詞再次切分,提高召回率,適合用于搜索引擎分詞;
paddle模式————利用PaddlePaddle深度學(xué)習(xí)框架,訓(xùn)練序列標(biāo)注(雙向GRU)網(wǎng)絡(luò)模型實(shí)現(xiàn)分詞。同時(shí)支持詞性標(biāo)注。
:return:
'''
# jieba.enable_paddle()
# paddle.fluid.install_check.run_check()
if not isinstance(text_content, str):
raise ValueError('文本字符串類型錯(cuò)誤!')
if not isinstance(key_word_need_num, int):
raise ValueError('關(guān)鍵詞個(gè)數(shù)類型錯(cuò)誤!')
if not isinstance(custom_words, list):
raise ValueError('自定義關(guān)鍵詞類型錯(cuò)誤!')
if not isinstance(stop_words, list):
raise ValueError('屏蔽關(guān)鍵詞類型錯(cuò)誤!')
if not isinstance(query_pattern, str):
raise ValueError('查詢模式類型錯(cuò)誤!')
# 添加自定義關(guān)鍵詞
for word in custom_words:
jieba.add_word(word)
if query_pattern == 'searchEngine':
key_words = jieba.cut_for_search(text_content)
elif query_pattern == 'entire':
key_words = jieba.cut(text_content, cut_all=True, use_paddle=True)
elif query_pattern == 'precision':
key_words = jieba.cut(text_content, cut_all=False, use_paddle=True)
else:
return []
# print("拆分后的詞: %s" % " ".join(key_words))
# 過(guò)濾后的關(guān)鍵詞
stop_words = set(stop_words)
word_count = Counter()
for word in key_words:
if len(word) > 1 and word not in stop_words:
word_count[word] += 1
# res_words = list()
# for data in word_count.most_common(key_word_need_num):
# res_words.append(data[0])
# return res_words
return word_count
def drawWordsCloud(word_count, save_img_filePath='', img_mask_filePath=''):
# print(word_count)
# print(type(word_count))
if len(img_mask_filePath) != 0:
img_mask = np.array(Image.open(img_mask_filePath)) #打開(kāi)遮罩圖片,將圖片轉(zhuǎn)換為數(shù)組
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫(kù)”,不支持中文
background_color="white", # 設(shè)置背景顏色
max_words=200, # 設(shè)置最大顯示的字?jǐn)?shù)
max_font_size=50, # 設(shè)置字體最大值
random_state=30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案
width=400,
height=200,
mask=img_mask
)
else:
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫(kù)”,不支持中文
background_color="white", # 設(shè)置背景顏色
max_words=200, # 設(shè)置最大顯示的字?jǐn)?shù)
max_font_size=50, # 設(shè)置字體最大值
random_state=30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案
width=400,
height=200
)
# 繪圖
wc.generate_from_frequencies(word_count) #從字典生成詞云
plt.imshow(wc) #顯示詞云
plt.axis('off') #關(guān)閉坐標(biāo)軸
plt.show() #顯示圖像
# 保存圖片
if len(save_img_filePath) != 0:
wc.to_file(save_img_filePath)
else:
pass
if __name__ == '__main__':
pass
# /Users/mac/Downloads/work/retailSoftware/公司項(xiàng)目/test.txt
text_file_path = "/Users/mac/Downloads/電子書/編程思想/相約星期二/相約星期二.txt"
# text_file_path = "/Users/mac/Downloads/work/retailSoftware/公司項(xiàng)目/test3.txt"
text_content = readText(text_file_path)
# print(text_content)
# print(JNI_API_getRecommondArticleKeyword(text_content))
img_mask_filePath = '/Users/mac/Desktop/截屏2021-08-20 下午4.02.10.png'
img_save_filePath = '/Users/mac/Downloads/test9.png'
drawWordsCloud(getRecommondArticleKeyword(text_content), img_save_filePath, img_mask_filePath)
到此這篇關(guān)于Python統(tǒng)計(jì)詞頻并繪制圖片(附完整代碼)的文章就介紹到這了,更多相關(guān)Python統(tǒng)計(jì)詞頻繪制圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Python實(shí)現(xiàn)簡(jiǎn)單的學(xué)生點(diǎn)名系統(tǒng)
現(xiàn)在的學(xué)生大部分都很積極,會(huì)主動(dòng)舉手回答問(wèn)題。但是,也會(huì)遇到一些不好的情況,比如年級(jí)越高主動(dòng)舉手的人越少,所以本文做了一個(gè)隨機(jī)的學(xué)生點(diǎn)名系統(tǒng)可以幫老師解決這些問(wèn)題2022-09-09
Python實(shí)現(xiàn)遍歷目錄的方法【測(cè)試可用】
這篇文章主要介紹了Python實(shí)現(xiàn)遍歷目錄的方法,涉及Python針對(duì)目錄與文件的遍歷、判斷、讀取相關(guān)操作技巧,需要的朋友可以參考下2017-03-03
Python實(shí)現(xiàn)在Excel文件中寫入圖表
這篇文章主要為大家介紹了如何利用Python語(yǔ)言實(shí)現(xiàn)在Excel文件中寫入一個(gè)比較簡(jiǎn)單的圖表,文中的實(shí)現(xiàn)方法講解詳細(xì),快動(dòng)手嘗試一下吧2022-05-05
Python+OpenCV 實(shí)現(xiàn)簡(jiǎn)單的高斯濾波(推薦)
這篇文章主要介紹了Python+OpenCV 實(shí)現(xiàn)簡(jiǎn)單的高斯濾波,在文中需要注意的是,這里我沒(méi)有特判當(dāng)sigma = 0的時(shí)候的情況,具體實(shí)現(xiàn)過(guò)程跟隨小編一起看看吧2021-09-09
python使用正則表達(dá)式匹配反斜杠\遇到的問(wèn)題
在學(xué)習(xí)Python正則式的過(guò)程中,有一個(gè)問(wèn)題一直困擾我,如何去匹配一個(gè)反斜杠(即“\”),下面這篇文章主要給大家介紹了關(guān)于python使用正則表達(dá)式匹配反斜杠\的相關(guān)資料,需要的朋友可以參考下2022-09-09
淺談Python中的zip()與*zip()函數(shù)詳解
這篇文章主要介紹了淺談Python中的zip()與*zip()函數(shù)詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
Python 隱藏輸入密碼時(shí)屏幕回顯的實(shí)例
今天小編就為大家分享一篇Python 隱藏輸入密碼時(shí)屏幕回顯的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
Python 數(shù)據(jù)可視化之Matplotlib詳解
這篇文章主要介紹了Python數(shù)據(jù)可視化庫(kù)seaborn的使用總結(jié),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2021-11-11
關(guān)于keras中卷積層Conv2D的學(xué)習(xí)記錄
這篇文章主要介紹了關(guān)于keras中卷積層Conv2D的學(xué)習(xí)記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

