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

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

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

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

其實也就是針對新手吧,我估計老手分分鐘,哈哈哈,我怕我忘了,隨手記錄下~

四個步驟吧:

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

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

import jieba
from collections import Counter
def get_words(txt):
    # 先分詞,得到詞語數(shù)組
    seg_list = jieba.cut(txt)
    # 開始計數(shù)
    c = Counter()
    for x in seg_list:
        if len(x)>1 and x != '\r\n':
            c[x] += 1
    word_list = []
    print('常用詞頻度統(tǒng)計結(jié)果')
     # 統(tǒng)計前99個詞
    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)計前99個詞
            writeFile.write(str(k))
            writeFile.write(str(v))
            writeFile.write('\n')
    print(word_list)
    # ['發(fā)展','平安']
    return word_list

3. 生成云圖

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

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)
  # 先實例化一個詞云對象
  wc = wordcloud.WordCloud(width=image.shape[0],     # 詞云圖寬度同原圖片寬度
                          height=image.shape[1],
                          background_color='white',  # 背景顏色白色
                          font_path='Arial Unicode.ttf',    # 指定字體路徑,微軟雅黑,可從自帶的字體庫中找
                          mask=image,   # mask 指定詞云形狀圖片,默認為矩形
                          scale=3)      # 默認為1,越大越清晰
  # 生成詞云
  wc.generate(string)
  # 保存成文件,output_wordcloud.png,詞云圖
  wc.to_file('dist/output_wordcloud.png')
  # 彈出圖片顯示
  alert_image('dist/output_wordcloud.png')

4. 顯示詞云圖

matplotlib是一個繪圖庫,可以將圖片顯示出來,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
  # 此時 lena 就已經(jīng)是一個 np.array 了,可以對它進行任意處理
  lena.shape #(512, 512, 3)
  plt.imshow(lena) # 顯示圖片
  plt.axis('off') # 不顯示坐標軸
  plt.show()

這就可以了!

其他文件

準備好文件實驗:

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)計詞頻,生成out.txt,展示詞語和詞頻 如發(fā)展218 堅持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)計結(jié)果')
     # 統(tǒng)計前99個詞
    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)計前99個詞
            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
    # 此時 lena 就已經(jīng)是一個 np.array 了,可以對它進行任意處理
    lena.shape #(512, 512, 3)
    plt.imshow(lena) # 顯示圖片
    plt.axis('off') # 不顯示坐標軸
    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)
    # 生成詞云圖片,先實例化一個詞云對象
    wc = wordcloud.WordCloud(width=image.shape[0],     # 詞云圖寬度同原圖片寬度
                            height=image.shape[1],
                            background_color='white',  # 背景顏色白色
                            font_path='Arial Unicode.ttf',    # 指定字體路徑,微軟雅黑,可從win自帶的字體庫中找
                            mask=image,   # mask 指定詞云形狀圖片,默認為矩形
                            scale=3)      # 默認為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')

運行

記得先pip3 install jieba imageio wordcloud matplotlib然后python3 generate_cloud_image.py??:文件在同一目錄,進到這個目錄下運行命令

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

相關(guān)文章

  • 使用numpy和PIL進行簡單的圖像處理方法

    使用numpy和PIL進行簡單的圖像處理方法

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

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

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

    pandas基礎?Series與Dataframe與numpy對二進制文件輸入輸出

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

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

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

    python3 selenium自動化 下拉框定位的例子

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

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

    Flask是一個使用Python編寫的輕量級Web應用框架。其WSGI工具箱采用 Werkzeug,模板引擎則使用Jinja2。Flask使用 BSD 授權(quán)。Flask也被稱為“microframework”,因為它使用簡單的核心,用 extension 增加其他功能,本篇帶你用Flask實現(xiàn)swagger在線文檔與接口測試
    2022-07-07
  • python怎么提高計算速度

    python怎么提高計算速度

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

    python網(wǎng)絡編程學習筆記(二):socket建立網(wǎng)絡客戶端

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

    Python PyTorch實現(xiàn)Timer計時器

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

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

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

最新評論