Python统计词频并绘制图片(附完整代码)

 更新时间:2021年08月25日 15:03:55   作者:繁星蓝雨  
这篇文章主要介绍了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)


到此这篇关于Python统计词频并绘制图片(附完整代码)的文章就介绍到这了,更多相关Python统计词频绘制图片内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现栅栏密码的加密解密方法详解

    Python实现栅栏密码的加密解密方法详解

    这篇文章主要介绍了Python实现栅栏密码的加密解密方法,所谓栅栏密码,就是把要加密的明文分成N个一组,然后把每组的第1个字连起来,形成一段无规律的话。不过栅栏密码本身有一个潜规则,就是组成栅栏的字母一般不会太多
    2023-01-01
  • Python 深入了解opencv图像分割算法

    Python 深入了解opencv图像分割算法

    本文主要介绍了Python通过opencv实现图像分割的详细过程与代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • 基于Python实现全自动二维码识别

    基于Python实现全自动二维码识别

    这篇文章主要为大家详细介绍了如何基于Python实现全自动二维码识别功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-11-11
  • python的tkinter布局之简单的聊天窗口实现方法

    python的tkinter布局之简单的聊天窗口实现方法

    这篇文章主要介绍了python的tkinter布局之简单的聊天窗口实现方法,对于tkinter用法做了初步的介绍与应用展示,需要的朋友可以参考下
    2014-09-09
  • python中的多重继承实例讲解

    python中的多重继承实例讲解

    这篇文章主要介绍了python中的多重继承实例讲解,本文着重讲解寻找父类的顺序,分为经典类和新式类,需要的朋友可以参考下
    2014-09-09
  • 150行Python代码实现带界面的数独游戏

    150行Python代码实现带界面的数独游戏

    这篇文章主要介绍了150行Python代码实现带界面的数独游戏,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-04-04
  • 基于Python实现24点游戏的示例代码

    基于Python实现24点游戏的示例代码

    这篇文章主要为大家详细介绍了如何利用Python实现24点游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-12-12
  • 用python的seaborn画数值箱型图

    用python的seaborn画数值箱型图

    大家好,本篇文章主要讲的是用python的seaborn画数值箱型图,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • Python中使用pypdf2合并、分割、加密pdf文件的代码详解

    Python中使用pypdf2合并、分割、加密pdf文件的代码详解

    这篇文章主要介绍了Python中使用pypdf2合并、分割、加密pdf文件的代码,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-05-05
  • 利用keras加载训练好的.H5文件,并实现预测图片

    利用keras加载训练好的.H5文件,并实现预测图片

    今天小编就为大家分享一篇利用keras加载训练好的.H5文件,并实现预测图片,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01

最新评论