python實現詞雲圖


引言

最近再參加網頁設計大賽,任務量都在網頁設計和網頁修改,以至於落了好多天學習大數據的知識。今天比賽結束,正好寫一篇網頁大賽用到的技術

正文

我們做的是一個豆瓣top250數據分析的一個網頁,其中有一項技術是用到了詞雲,今天正好把這項技術說說。

具體怎么做的呢,首先我們先爬取了豆瓣top250 220條關於某個電影的短評,然后將短評存到數據庫,讀取數據庫,將關於該部電影的短評組成一句話,進行jieba分詞,然后再過濾掉停用詞,制作詞雲圖,最后保存詞雲圖.

步驟

1、導包

## 包的作用
import jieba  #分詞
from wordcloud import WordCloud  #詞雲
from PIL import Image   #圖片處理
import numpy as np  #將圖片變成數組
import collections  #計數器
from matplotlib import pyplot as plt  #繪圖
import sqlite3  #數據庫

2、讀取數據,並返回數據

def get_data(db_name,sql):
    #連接數據庫
    conn = sqlite3.connect(db_name)
    #獲取游標
    cursor = conn.cursor()
    #執行sql語句
    data = cursor.execute(sql)
    text = ""
    #拼接信息
    for item in data:
        text += item[0]+" "
    cursor.close()
    #關閉數據庫
    conn.close()
    return text

3、進行分詞,並返回字典。(name:對應的單詞,value:單詞出現的個數)

def cut_word(text):
    #分詞:cut_all=False:精確模式 HMM=True:使用隱式馬爾科夫
    cut = jieba.cut(text,cut_all=False,HMM=True)
    object_list = []
    #讀取停用詞
    with open("stop_word.txt", 'r', encoding='UTF-8') as meaninglessFile:
        stopwords = set(meaninglessFile.read().split('\n'))
    stopwords.add(' ')
    #如果單詞不在停用詞里,則添加
    for word in cut:
        if word not in stopwords:
            object_list.append(word)
    #collections.Counter 計數器,統計單詞個數
    word_counts = collections.Counter(object_list)
    print(word_counts)
    return word_counts

4、生成詞雲圖並保存

def get_cloud(word_counts,i):
    #遮罩圖:必須是白底的
    img = Image.open(r'./img/tree.jpg')
    img_array = np.array(img)  #將圖片變為數組
    wc = WordCloud(
        background_color = 'white', # 背景顏色
        mask = img_array,  #遮罩圖片
        font_path = 'msyh.ttc'  #字體樣式

    )
    wc.generate_from_frequencies(word_counts)  #生成詞雲圖
    fig = plt.figure(1)
    plt.imshow(wc)  # 顯示詞雲
    plt.axis('off') # 關閉保存
    #plt.show()
    #調整邊框
    plt.subplots_adjust(top=0.99, bottom=0.01, right=0.99, left=0.01, hspace=0, wspace=0)
    #保存圖片
    plt.savefig(r'./movie_img/movie{0}.jpg'.format(i),dpi = 500)

5、總的代碼

#-*- codeing = utf-8 -*-
#@Time : 2020/11/14 22:16
#@Author : 楊曉
#@File : testCloud.py
#@Software: PyCharm
## 包的作用
import jieba  #分詞
from wordcloud import WordCloud  #詞雲
from PIL import Image   #圖片處理
import numpy as np  #將圖片變成數組
import collections  #計數器
from matplotlib import pyplot as plt  #繪圖
import sqlite3  #數據庫
# 獲取短評信息
def get_data(db_name,sql):
    #連接數據庫
    conn = sqlite3.connect(db_name)
    #獲取游標
    cursor = conn.cursor()
    #執行sql語句
    data = cursor.execute(sql)
    text = ""
    for item in data:
        text += item[0]+" "
    cursor.close()
    #關閉數據庫
    conn.close()
    return text

def cut_word(text):
    #分詞:cut_all=False:精確模式 HMM=True:使用隱式馬爾科夫
    cut = jieba.cut(text,cut_all=False,HMM=True)
    object_list = []
    #讀取停用詞
    with open("stop_word.txt", 'r', encoding='UTF-8') as meaninglessFile:
        stopwords = set(meaninglessFile.read().split('\n'))
    stopwords.add(' ')
    #如果單詞不在停用詞里,則添加
    for word in cut:
        if word not in stopwords:
            object_list.append(word)
    #collections.Counter 計數器,統計單詞個數
    word_counts = collections.Counter(object_list)
    print(word_counts)
    return word_counts
def get_cloud(word_counts,i):
    #遮罩圖:必須是白底的
    img = Image.open(r'./img/tree.jpg')
    img_array = np.array(img)  #將圖片變為數組
    wc = WordCloud(
        background_color = 'white', # 背景顏色
        mask = img_array,  #遮罩圖片
        font_path = 'msyh.ttc'  #字體樣式

    )
    wc.generate_from_frequencies(word_counts)  #生成詞雲圖
    fig = plt.figure(1)
    plt.imshow(wc)  # 顯示詞雲
    plt.axis('off') # 關閉保存
    #plt.show()
    #調整邊框
    plt.subplots_adjust(top=0.99, bottom=0.01, right=0.99, left=0.01, hspace=0, wspace=0)
    #保存圖片
    plt.savefig(r'./movie_img/movie{0}.jpg'.format(i),dpi = 500)

if __name__ == '__main__':
    for i in range(1,251):
        #編寫查詢語句
        sql = "select info from movie"+str(i)
        text = get_data('duanping',sql)
        word_counts = cut_word(text)
        get_cloud(word_counts,i)

因為要生成250個詞雲圖,所有才有for循環。具體要求請讀者按照自己的需求更改main函數代碼

運行結果:

肖申克的救贖:

王霸別姬


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM