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

基于python生成詞云圖的代碼示例

 更新時(shí)間:2023年11月16日 08:32:07   作者:顏醬  
這篇文章主要個(gè)介紹了如何基于python生成詞云圖的代碼示例,文中有詳細(xì)的代碼示例喝圖文講解,對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下

類似生成各種形狀的云圖,我也會(huì)啦!

其實(shí)也就是針對(duì)新手吧,我估計(jì)老手分分鐘,哈哈哈,我怕我忘了,隨手記錄下~

四個(gè)步驟吧:

  • 讀文件
  • 分詞
  • 生成詞云圖
  • 顯示詞云圖

1. 讀文件

使用了下 codecs 庫,讀取內(nèi)容更方便。

import codecs
def get_file_content(filePath):
  with codecs.open(filePath, 'r', 'utf-8') as f:
      txt = f.read()
  return txt

2. 分詞

jieba是一個(gè)分詞庫,可以將一段文本分割成詞語。cut 是將文本精確切分開,不存在冗余詞語。比如顏醬是一個(gè)厲害的廚師,會(huì)變成['顏醬', '厲害', '廚師']。 Counter是一個(gè)計(jì)數(shù)器,可以統(tǒng)計(jì)詞語出現(xiàn)的次數(shù),most_common 是取出最常用的詞語。

import jieba
from collections import Counter
def get_words(txt):
    # 先分詞,得到詞語數(shù)組
    seg_list = jieba.cut(txt)
    # 開始計(jì)數(shù)
    c = Counter()
    for x in seg_list:
        if len(x)>1 and x != '\r\n':
            c[x] += 1
    word_list = []
    print('常用詞頻度統(tǒng)計(jì)結(jié)果')
     # 統(tǒng)計(jì)前99個(gè)詞
    for (k,v) in c.most_common(99):
        word_list.append(str(k))
    # 將詞語生成文本文件
    file = open("./dist/out_words.txt", 'w').close()
    with open("./dist/out_words.txt",'a+',encoding='utf-8') as writeFile:
        for (k,v) in c.most_common(99):    # 統(tǒng)計(jì)前99個(gè)詞
            writeFile.write(str(k))
            writeFile.write(str(v))
            writeFile.write('\n')
    print(word_list)
    # ['發(fā)展','平安']
    return word_list

3. 生成云圖

wordcloud 是一個(gè)詞云庫,可以將詞語生成詞云圖片。

import wordcloud;
def generate_cloud_image(file_path, shape_image_path):
  word_list = get_words(get_file_content(file_path))
  string = ' '.join(word_list)
  # 讀取詞云形狀圖片
  image = imageio.v2.imread(shape_image_path)
  # 先實(shí)例化一個(gè)詞云對(duì)象
  wc = wordcloud.WordCloud(width=image.shape[0],     # 詞云圖寬度同原圖片寬度
                          height=image.shape[1],
                          background_color='white',  # 背景顏色白色
                          font_path='Arial Unicode.ttf',    # 指定字體路徑,微軟雅黑,可從自帶的字體庫中找
                          mask=image,   # mask 指定詞云形狀圖片,默認(rèn)為矩形
                          scale=3)      # 默認(rèn)為1,越大越清晰
  # 生成詞云
  wc.generate(string)
  # 保存成文件,output_wordcloud.png,詞云圖
  wc.to_file('dist/output_wordcloud.png')
  # 彈出圖片顯示
  alert_image('dist/output_wordcloud.png')

4. 顯示詞云圖

matplotlib是一個(gè)繪圖庫,可以將圖片顯示出來,plt 用于顯示圖片,mpimg 用于讀取圖片。

#
# plt用于顯示圖片
import matplotlib.pyplot as plt
# mpimg 用于讀取圖片
import matplotlib.image as mpimg
def alert_image(image_path):
  # 這里是讓詞云圖彈出來顯示
  lena = mpimg.imread(image_path) # 讀取和代碼處于同一目錄下的 lena.png
  # 此時(shí) lena 就已經(jīng)是一個(gè) np.array 了,可以對(duì)它進(jìn)行任意處理
  lena.shape #(512, 512, 3)
  plt.imshow(lena) # 顯示圖片
  plt.axis('off') # 不顯示坐標(biāo)軸
  plt.show()

這就可以了!

其他文件

準(zhǔn)備好文件實(shí)驗(yàn):

input.txt

input.txt

cloud.jpg

generate_cloud_image.py

generate_cloud_image.py:

import codecs
import jieba
import imageio
import wordcloud
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from collections import Counter
# def get_words(txt):...
# def get_file_content:...
# def alert_image(image_path):...
# def generate_cloud_image(file_path, shape_image_path):...
generate_cloud_image('input.txt', 'cloud.jpg')

完整版:

import codecs
import jieba
import imageio
import wordcloud
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from collections import Counter
#  get_words函數(shù)用于統(tǒng)計(jì)詞頻,生成out.txt,展示詞語和詞頻 如發(fā)展218 堅(jiān)持170
def get_words(txt):
    seg_list = jieba.cut(txt)
    c = Counter()
    for x in seg_list:
        if len(x)>1 and x != '\r\n':
            c[x] += 1
    word_list = []
    print('常用詞頻度統(tǒng)計(jì)結(jié)果')
     # 統(tǒng)計(jì)前99個(gè)詞
    for (k,v) in c.most_common(99):
        word_list.append(str(k))

    file = open("./out_words.txt", 'w').close()
    with open("./out_words.txt",'a+',encoding='utf-8') as writeFile:
        for (k,v) in c.most_common(99):    # 統(tǒng)計(jì)前99個(gè)詞
            writeFile.write(str(k))
            writeFile.write(str(v))
            writeFile.write('\n')
    print(word_list)
    # ['發(fā)展','平安']
    return word_list

def get_file_content(filePath):
    with codecs.open(filePath, 'r', 'utf-8') as f:
        txt = f.read()
    return txt
def alert_image(image_path):
    # 這里是讓詞云圖彈出來顯示
    lena = mpimg.imread(image_path) # 讀取和代碼處于同一目錄下的 lena.png
    # 此時(shí) lena 就已經(jīng)是一個(gè) np.array 了,可以對(duì)它進(jìn)行任意處理
    lena.shape #(512, 512, 3)
    plt.imshow(lena) # 顯示圖片
    plt.axis('off') # 不顯示坐標(biāo)軸
    plt.show()

# 根據(jù)文件生成詞云圖,file_path是文本文件路徑,shape_image_path是詞云圖的圖片途徑
def generate_cloud_image(file_path, shape_image_path):
    word_list = get_words(get_file_content(file_path))
    string = ' '.join(word_list)
    # 讀取詞云形狀圖片
    image = imageio.v2.imread(shape_image_path)
    # 生成詞云圖片,先實(shí)例化一個(gè)詞云對(duì)象
    wc = wordcloud.WordCloud(width=image.shape[0],     # 詞云圖寬度同原圖片寬度
                            height=image.shape[1],
                            background_color='white',  # 背景顏色白色
                            font_path='Arial Unicode.ttf',    # 指定字體路徑,微軟雅黑,可從win自帶的字體庫中找
                            mask=image,   # mask 指定詞云形狀圖片,默認(rèn)為矩形
                            scale=3)      # 默認(rèn)為1,越大越清晰
    # 再給詞云
    wc.generate(string)
    # 保存成文件,output_wordcloud.png,詞云圖
    wc.to_file('output_wordcloud.png')
    alert_image('output_wordcloud.png')

generate_cloud_image('input.txt', 'cloud.jpg')

運(yùn)行

記得先pip3 install jieba imageio wordcloud matplotlib然后python3 generate_cloud_image.py??:文件在同一目錄,進(jìn)到這個(gè)目錄下運(yùn)行命令

以上就是基于python生成詞云圖的代碼示例的詳細(xì)內(nèi)容,更多關(guān)于python生成詞云圖的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 使用numpy和PIL進(jìn)行簡單的圖像處理方法

    使用numpy和PIL進(jìn)行簡單的圖像處理方法

    今天小編就為大家分享一篇使用numpy和PIL進(jìn)行簡單的圖像處理方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • python?-?sqlachemy另類用法思路詳解

    python?-?sqlachemy另類用法思路詳解

    這篇文章主要介紹了python?-?sqlachemy另類用法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-12-12
  • pandas基礎(chǔ)?Series與Dataframe與numpy對(duì)二進(jìn)制文件輸入輸出

    pandas基礎(chǔ)?Series與Dataframe與numpy對(duì)二進(jìn)制文件輸入輸出

    這篇文章主要介紹了pandas基礎(chǔ)Series與Dataframe與numpy對(duì)二進(jìn)制文件輸入輸出,series是一種一維的數(shù)組型對(duì)象,它包含了一個(gè)值序列和一個(gè)數(shù)據(jù)標(biāo)簽
    2022-07-07
  • Python數(shù)據(jù)分析matplotlib折線圖案例處理

    Python數(shù)據(jù)分析matplotlib折線圖案例處理

    這篇文章主要介紹了Python數(shù)據(jù)分析matplotlib折線圖案例處理,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-08-08
  • python3 selenium自動(dòng)化 下拉框定位的例子

    python3 selenium自動(dòng)化 下拉框定位的例子

    今天小編就為大家分享一篇python3 selenium自動(dòng)化 下拉框定位的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • Flask實(shí)現(xiàn)swagger在線文檔與接口測試流程詳解

    Flask實(shí)現(xiàn)swagger在線文檔與接口測試流程詳解

    Flask是一個(gè)使用Python編寫的輕量級(jí)Web應(yīng)用框架。其WSGI工具箱采用 Werkzeug,模板引擎則使用Jinja2。Flask使用 BSD 授權(quán)。Flask也被稱為“microframework”,因?yàn)樗褂煤唵蔚暮诵?,?nbsp;extension 增加其他功能,本篇帶你用Flask實(shí)現(xiàn)swagger在線文檔與接口測試
    2022-07-07
  • python怎么提高計(jì)算速度

    python怎么提高計(jì)算速度

    在本篇文章里小編給大家分享的是一篇關(guān)于python中如何提高計(jì)算速度的技術(shù)文章,需要的朋友們可以學(xué)習(xí)下。
    2020-06-06
  • python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(二):socket建立網(wǎng)絡(luò)客戶端

    python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(二):socket建立網(wǎng)絡(luò)客戶端

    看了這一節(jié),突然之間對(duì)python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(1)中的一些不理解的問題有了認(rèn)識(shí),至少明白了socket是怎么回事。這里關(guān)于socket的起源等問題就不做筆記記錄了,直接進(jìn)入主題
    2014-06-06
  • Python PyTorch實(shí)現(xiàn)Timer計(jì)時(shí)器

    Python PyTorch實(shí)現(xiàn)Timer計(jì)時(shí)器

    這篇文章主要為大家詳細(xì)介紹了Python PyTorch如何實(shí)現(xiàn)簡單的Timer計(jì)時(shí)器,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-08-08
  • python實(shí)現(xiàn)多線程并得到返回值的示例代碼

    python實(shí)現(xiàn)多線程并得到返回值的示例代碼

    這篇文章主要介紹了python實(shí)現(xiàn)多線程并得到返回值的相關(guān)知識(shí),包括帶有返回值的多線程及實(shí)現(xiàn)過程解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05

最新評(píng)論