1. 程式人生 > 實用技巧 >爬取資料分析——將豆瓣電影top250以詞雲的方式展現

爬取資料分析——將豆瓣電影top250以詞雲的方式展現

根據爬取到的豆瓣top250電影資訊,根據一句話概述,首先使用jieba分詞工具進行分詞,再使用wordcloud進行詞雲展示

# -*- codeing = utf-8 -*-
# @Time : 2020/7/14 0:11
# @Author: 小菜菜最菜
# @File : testCloud.py
# @Software : PyCharm

import jieba
from matplotlib import pyplot as plt
from wordcloud import WordCloud
from PIL import Image   # 圖片處理
import numpy as np      # 矩陣運算
import sqlite3

# 這裡已將資料儲存在movie.db中,儲存方法可見前面部落格,使用的資料庫為sqlite3
conn = sqlite3.connect('movie.db')
cur = conn.cursor()
sql = 'select instroduction from movie250'
data = cur.execute(sql)
text = ""
for item in data:
    text = text + item[0]
cur.close()
conn.close()
print(text)
print('-----------------')


# 分詞
cut = jieba.cut(text)
string = ' '.join(cut)
print(len(string))


# 畫圖
img = Image.open(r'./static/assets/img/tree.jpg')
img_array = np.array(img)# 圖片轉化為陣列
wc = WordCloud(
    background_color='white',
    mask = img_array,
    font_path = "msyh.ttc"
)
wc.generate_from_text(string)



#繪製圖片
fig = plt.figure(1)
plt.imshow(wc)
plt.axis('off')   # 是否顯示座標軸
# plt.show()    # 顯示生成的詞雲圖片


# 輸出詞雲圖片到檔案
plt.savefig(r'.\static\assets\img\word.jpg',dpi=500)

生成的詞雲圖片為: