Python统计词频并绘制图片(附完整代码)
作者:繁星蓝雨 发布时间:2022-01-01 09:28:24
标签:Python,统计,词频,绘图
效果
1 实现代码
读取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: 需要的关键词数量
:param custom_words: 自定义关键词
:param stop_words: 不查询关键词
:param query_pattern:
precision:精确模式————试图将句子最精确地切开,适合文本分析;
entire:全模式————把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;
searchEngine:搜索引擎模式————在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词;
paddle模式————利用PaddlePaddle深度学习框架,训练序列标注(双向GRU)网络模型实现分词。同时支持词性标注。
:return:
'''
# jieba.enable_paddle()
# paddle.fluid.install_check.run_check()
if not isinstance(text_content, str):
raise ValueError('文本字符串类型错误!')
if not isinstance(key_word_need_num, int):
raise ValueError('关键词个数类型错误!')
if not isinstance(custom_words, list):
raise ValueError('自定义关键词类型错误!')
if not isinstance(stop_words, list):
raise ValueError('屏蔽关键词类型错误!')
if not isinstance(query_pattern, str):
raise ValueError('查询模式类型错误!')
# 添加自定义关键词
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))
# 过滤后的关键词
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)) #打开遮罩图片,将图片转换为数组
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 设置中文字体,词云默认字体是“DroidSansMono.ttf字体库”,不支持中文
background_color="white", # 设置背景颜色
max_words=200, # 设置最大显示的字数
max_font_size=50, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=400,
height=200,
mask=img_mask
)
else:
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 设置中文字体,词云默认字体是“DroidSansMono.ttf字体库”,不支持中文
background_color="white", # 设置背景颜色
max_words=200, # 设置最大显示的字数
max_font_size=50, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=400,
height=200
)
# 绘图
wc.generate_from_frequencies(word_count) #从字典生成词云
plt.imshow(wc) #显示词云
plt.axis('off') #关闭坐标轴
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 #词云展示库
import matplotlib.pyplot as plt #图像展示库
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: 需要的关键词数量
:param custom_words: 自定义关键词
:param stop_words: 不查询关键词
:param query_pattern:
precision:精确模式————试图将句子最精确地切开,适合文本分析;
entire:全模式————把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;
searchEngine:搜索引擎模式————在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词;
paddle模式————利用PaddlePaddle深度学习框架,训练序列标注(双向GRU)网络模型实现分词。同时支持词性标注。
:return:
'''
# jieba.enable_paddle()
# paddle.fluid.install_check.run_check()
if not isinstance(text_content, str):
raise ValueError('文本字符串类型错误!')
if not isinstance(key_word_need_num, int):
raise ValueError('关键词个数类型错误!')
if not isinstance(custom_words, list):
raise ValueError('自定义关键词类型错误!')
if not isinstance(stop_words, list):
raise ValueError('屏蔽关键词类型错误!')
if not isinstance(query_pattern, str):
raise ValueError('查询模式类型错误!')
# 添加自定义关键词
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))
# 过滤后的关键词
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)) #打开遮罩图片,将图片转换为数组
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 设置中文字体,词云默认字体是“DroidSansMono.ttf字体库”,不支持中文
background_color="white", # 设置背景颜色
max_words=200, # 设置最大显示的字数
max_font_size=50, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=400,
height=200,
mask=img_mask
)
else:
wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 设置中文字体,词云默认字体是“DroidSansMono.ttf字体库”,不支持中文
background_color="white", # 设置背景颜色
max_words=200, # 设置最大显示的字数
max_font_size=50, # 设置字体最大值
random_state=30, # 设置有多少种随机生成状态,即有多少种配色方案
width=400,
height=200
)
# 绘图
wc.generate_from_frequencies(word_count) #从字典生成词云
plt.imshow(wc) #显示词云
plt.axis('off') #关闭坐标轴
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/公司项目/test.txt
text_file_path = "/Users/mac/Downloads/电子书/编程思想/相约星期二/相约星期二.txt"
# text_file_path = "/Users/mac/Downloads/work/retailSoftware/公司项目/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)
来源:https://blog.csdn.net/qq_33375598/article/details/119856008
0
投稿
猜你喜欢
- 在使用pytorch的时候,经常会涉及到两种数据格式tensor和ndarray之间的转换,这里总结一下两种格式的转换:1. tensor
- 1、文件添加方式:pycharm提供了一个在新建文件自动生成文件头注释的功能,可以实现自动生成运行环境,作者、日期等必要信息,使用比较方便,
- <script> Function.prototype.$bind=function(object) {  
- kNN(k-nearest neighbor)是一种基本的分类与回归的算法。这里我们先只讨论分类中的kNN算法。k邻近算法的输入为实例的特征
- 导语:使用 python-plotly 模块来进行压测数据的绘制,并且生成静态 html 页面结果展示。不少小伙伴在开发过程中都有对模块进行
- 本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下:打开文件:在python3中,
- import siximport timeit#查找任何特定代码执行的确切时间from ecdsa.curves import curves
- 一、Python 切片的一些用法alist = [3,4,5,6,7,9,11,13,15,17]print(alist[::]) # 返回
- 一、前言今天我们将用Python来创建一个属于自己的音乐播放器。为此,我们将使用三个软件包:Tkinter:用于UIPygame:播放音乐o
- 如何在浏览器地址栏显示自己的Favicons小图标?显示效果如下列网站的图标:Google网易163上面两个网站都设置了自己的Favicon
- 有一个优秀的库可以使用————demjson示范链接http
- 今天是Firefox3的2008下载日(貌似北京时间是6.18的凌晨1:00),这就意味着Firefox3正式发布了。Firefox3有众多
- 1.查看mysql上都有哪些库mysql> show databases \G***************************
- 查看python搜索包的路径的实现方法:python搜索包的路径存储在sys.path下查看方法:import syssys.path临时添
- 问题场景有时候,在编写一段http接口请求程序时,发现代码中的header头和请求体中都是原网页中一样,但是,在实际请求时,接口却返回404
- 简述和GNU一样,YAML是一个递归着说“不”的名字。不同的是,GNU对UNIX说不,YAML说不的对象是XML。YAML不是XML。为什么
- 如何在页面错误时向数据库中添加记录?在ASP中,我在页面中添加了On Error Resume Next错误命令,以消除和避免程序错误。现在
- MSDN:包含正在 SQL Server 实例上运行的进程的相关信息。这些进程可以是客户端进程或系统进程。 视图中主要的字段: 1. Spi
- 本文实例讲述了python提取内容关键词的方法。分享给大家供大家参考。具体分析如下:一个非常高效的提取内容关键词的python代码,这段代码
- 本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下#!/usr/bin/env python# -*- c