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
投稿
猜你喜欢
- 在我们做搜索的时候经常要用到模糊查询 (注:其中name1,name2,name3,name4为数据库字段) 1.方法 sql="
- 前文主要纠正title用法上的几点误区,其实除链接和表单的常规标签用法。在内容组织方面还有大潜力待发掘,比如写网志经常会有针对词、短语说明的
- 效果图:代码如下:<!DOCTYPE html><html> <head> <meta chars
- 注:此方法可用于配置gitlab也可用于配置github1.在github中创建一个账号:https://github.com/join?s
- 在大多数语音识别任务中,我们都缺少文本和音频特征的alignment,Connectionist Temporal Classificati
- Access允许您在数据库表中包含附件。通过利用微软的对象链接和嵌入(OLE)技术,您可以将照片、图表、文档及其他文件存储在您的Access
- math模块# 数学相关模块import mathr = math.floor(3.2) # 向下取整print(r)r = math.ce
- 本文实例讲述了Vue + Node.js + MongoDB图片上传组件实现图片预览和删除功能。分享给大家供大家参考,具体如下:公司要写一些
- 介绍海象运算符,即 := ,在 PEP 572 中被提出,并在 Python3.8 版本中发布。海象运算符的英文原名叫Assignment
- 本文实例为大家分享了python实现人机五子棋的具体代码,供大家参考,具体内容如下图形界面引用PyQt5,还有socket通信。可以局域网对
- 一、下载MySql,安装MySql官网下载MySql数据库官网下载链接地址:https://dev.mysql.com/downloads/
- 任何一门编程语言都离不开对各种工具包的使用,工具包的管理就显得异常重要了。Go 的包管理方式是逐渐演进的,本文介绍Go语言的两种包管理模式。
- 本文实例讲述了Python上下文管理器类和上下文管理器装饰器contextmanager用法。分享给大家供大家参考,具体如下:一. 什么是上
- 本文实例为大家分享了JS HTML5拖拽上传图片预览的具体代码,供大家参考,具体内容如下1.文件API:(File API)file类型的的
- 一、MongoDB对MySQL常用的SQL语句对应的实现 —————————————— MySQL: SELECT * FROM user
- 前言对于刚刚下载好的pycharm,初学者使用会有一些问题,这里将介绍关于字体,背景,这些简单的设置将会提升编程的舒适度(下面以PyChar
- python制作超级玛丽游戏,供大家参考,具体内容如下这篇文章,我们优先介绍超级玛丽游戏中的多状态跳跃,和行走地图拖动的原理,然后实现。并实
- 处理多个数据和多文件时,使用for循环的速度非常慢,此时需要用多线程来加速运行进度,常用的模块为multiprocess和joblib,下面
- 数据类型:定义列中可以存储什么数据以及该数据实际怎样存储的基本规则。数据类型用于以下目的:1、允许限制可存储在列中的数据。如:数值数据类型列
- 通常程序会被编写为一个顺序执行并完成一个独立任务的代码。如果没有特别的需求,最好总是这样写代码,因为这种类型的程序通常很容易写,也很容易维护