欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2021年08月25日 15:03:55   作者:繁星藍(lán)雨  
這篇文章主要介紹了Python統(tǒng)計(jì)詞頻并繪制圖片(附完整代碼)本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

效果

請?zhí)砑訄D片描述
請?zhí)砑訄D片描述
請?zhí)砑訄D片描述

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:精確模式————試圖將句子最精確地切開,適合文本分析;
    entire:全模式————把句子中所有的可以成詞的詞語都掃描出來, 速度非???,但是不能解決歧義;
    searchEngine:搜索引擎模式————在精確模式的基礎(chǔ)上,對長詞再次切分,提高召回率,適合用于搜索引擎分詞;
    paddle模式————利用PaddlePaddle深度學(xué)習(xí)框架,訓(xùn)練序列標(biāo)注(雙向GRU)網(wǎng)絡(luò)模型實(shí)現(xiàn)分詞。同時支持詞性標(biāo)注。
    :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('關(guān)鍵詞個數(shù)類型錯誤!')
    if not isinstance(custom_words, list):
        raise ValueError('自定義關(guān)鍵詞類型錯誤!')
    if not isinstance(stop_words, list):
        raise ValueError('屏蔽關(guān)鍵詞類型錯誤!')
    if not isinstance(query_pattern, str):
        raise ValueError('查詢模式類型錯誤!')

    # 添加自定義關(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ā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)) #打開遮罩圖片,將圖片轉(zhuǎn)換為數(shù)組
        wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫”,不支持中文
                                 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字體庫”,不支持中文
                                 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    #詞云展示庫
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: 需要的關(guān)鍵詞數(shù)量
    :param custom_words: 自定義關(guān)鍵詞
    :param stop_words: 不查詢關(guān)鍵詞
    :param query_pattern:
    precision:精確模式————試圖將句子最精確地切開,適合文本分析;
    entire:全模式————把句子中所有的可以成詞的詞語都掃描出來, 速度非???,但是不能解決歧義;
    searchEngine:搜索引擎模式————在精確模式的基礎(chǔ)上,對長詞再次切分,提高召回率,適合用于搜索引擎分詞;
    paddle模式————利用PaddlePaddle深度學(xué)習(xí)框架,訓(xùn)練序列標(biāo)注(雙向GRU)網(wǎng)絡(luò)模型實(shí)現(xiàn)分詞。同時支持詞性標(biāo)注。
    :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('關(guān)鍵詞個數(shù)類型錯誤!')
    if not isinstance(custom_words, list):
        raise ValueError('自定義關(guān)鍵詞類型錯誤!')
    if not isinstance(stop_words, list):
        raise ValueError('屏蔽關(guān)鍵詞類型錯誤!')
    if not isinstance(query_pattern, str):
        raise ValueError('查詢模式類型錯誤!')

    # 添加自定義關(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ā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)) #打開遮罩圖片,將圖片轉(zhuǎn)換為數(shù)組
        wc = wordcloud.WordCloud(font_path='/Library/Fonts/Arial Unicode.ttf',# 設(shè)置中文字體,詞云默認(rèn)字體是“DroidSansMono.ttf字體庫”,不支持中文
                                 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字體庫”,不支持中文
                                 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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python內(nèi)建屬性getattribute攔截器使用詳解

    Python內(nèi)建屬性getattribute攔截器使用詳解

    這篇文章主要為大家介紹了Python內(nèi)建屬性getattribute攔截器使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • Python中將字符串轉(zhuǎn)換為列表的常用八種方法

    Python中將字符串轉(zhuǎn)換為列表的常用八種方法

    本文介紹了Python中將字符串轉(zhuǎn)換為列表的八種常用方法,包括split()方法、列表解析、正則表達(dá)式、str()函數(shù)、map()函數(shù)、re.split()、re.finditer()和逐字符遍歷,感興趣的可以了解一下
    2024-07-07
  • wxpython繪制圓角窗體

    wxpython繪制圓角窗體

    這篇文章主要為大家詳細(xì)介紹了wxpython繪制圓角窗體,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • 使用python3.0?對接美團(tuán)接口的實(shí)現(xiàn)示例

    使用python3.0?對接美團(tuán)接口的實(shí)現(xiàn)示例

    本文主要介紹了python3.0?對接美團(tuán)接口的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • python 6行代碼制作月歷生成器

    python 6行代碼制作月歷生成器

    這篇文章主要介紹了python如何用6行代碼制作月歷生成器,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-09-09
  • python數(shù)據(jù)可視化繪制火山圖示例

    python數(shù)據(jù)可視化繪制火山圖示例

    這篇文章主要為大家介紹了python數(shù)據(jù)可視化繪制火山圖示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • Python輕松管理與操作文件的技巧分享

    Python輕松管理與操作文件的技巧分享

    在日常開發(fā)中,我們經(jīng)常會遇到需要對文件進(jìn)行操作的場景,如讀寫文件、文件夾操作等。本文將為大家介紹一些 Python 中處理文件的實(shí)用技巧,讓你的工作更高效
    2023-05-05
  • Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)字典相關(guān)計(jì)算問題示例

    Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)字典相關(guān)計(jì)算問題示例

    這篇文章主要介紹了Python字典相關(guān)計(jì)算問題,結(jié)合實(shí)例形式總結(jié)分析了Python字典相關(guān)的最小值、最大值、排序等操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2018-02-02
  • python網(wǎng)絡(luò)編程之文件下載實(shí)例分析

    python網(wǎng)絡(luò)編程之文件下載實(shí)例分析

    這篇文章主要介紹了python網(wǎng)絡(luò)編程之文件下載實(shí)現(xiàn)方法,實(shí)例分析了Python基于FTP及http實(shí)現(xiàn)文件下載的技巧,需要的朋友可以參考下
    2015-05-05
  • 學(xué)習(xí)Python,你還不知道m(xù)ain函數(shù)嗎

    學(xué)習(xí)Python,你還不知道m(xù)ain函數(shù)嗎

    Python?中的?main?函數(shù)充當(dāng)程序的執(zhí)行點(diǎn),在?Python?編程中定義?main?函數(shù)是啟動程序執(zhí)行的必要條件。本文就來帶大家深入了解一下main函數(shù),感興趣的可以了解一下
    2022-09-09

最新評論