1. 程式人生 > >使用pyecharts繪製詞雲圖-淘寶商品評論展示

使用pyecharts繪製詞雲圖-淘寶商品評論展示

## 一、什麼是詞雲圖? 詞雲圖是一種用來展現高頻關鍵詞的視覺化表達,通過文字、色彩、圖形的搭配,產生有衝擊力地視覺效果,而且能夠傳達有價值的資訊。 製作詞雲圖的網站有很多,簡單方便,適合小批量操作。 BI軟體如Tableau、PowerBI也可以做,當然相比較web網站複雜一點。 在程式設計方面,JavaScript是製作詞雲圖的第一選擇,像D3、echarts都非常優秀。 python也有不少視覺化庫能製作詞雲圖,這次我們嘗試使用pyecharts。 先上效果圖: ![](https://upload-images.jianshu.io/upload_images/13723999-132300db19408268.gif?imageMogr2/auto-orient/strip) ![](https://upload-images.jianshu.io/upload_images/13723999-26d51da56e917d8c.gif?imageMogr2/auto-orient/strip) ![](https://upload-images.jianshu.io/upload_images/13723999-90c166bc97855090.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 二、pyecharts介紹 pyecharts是基於echarts的python庫,能夠繪製多種互動式圖表。 這次使用的pyecharts版本是1.7.1,python版本是3.6。 pyecharts提供了多種個性化配置方案,可以按需選擇。 ``` # 系列名稱,用於 tooltip 的顯示,legend 的圖例篩選。 series_name: str, # 系列資料項,[(word1, count1), (word2, count2)] data_pair: Sequence, # 詞雲圖輪廓,有 'circle', 'cardioid', 'diamond', 'triangle-forward', 'triangle', 'pentagon', 'star' 可選 shape: str = "circle", # 自定義的圖片(目前支援 jpg, jpeg, png, ico 的格式,其他的圖片格式待測試) # 該引數支援: # 1、 base64 (需要補充 data 頭); # 2、本地檔案路徑(相對或者絕對路徑都可以) # 注:如果使用了 mask_image 之後第一次渲染會出現空白的情況,再重新整理一次就可以了(Echarts 的問題) # Echarts Issue: https://github.com/ecomfe/echarts-wordcloud/issues/74 mask_image: types.Optional[str] = None, # 單詞間隔 word_gap: Numeric = 20, # 單詞字型大小範圍 word_size_range=None, # 旋轉單詞角度 rotate_step: Numeric = 45, # 距離左側的距離 pos_left: types.Optional[str] = None, # 距離頂部的距離 pos_top: types.Optional[str] = None, # 距離右側的距離 pos_right: types.Optional[str] = None, # 距離底部的距離 pos_bottom: types.Optional[str] = None, # 詞雲圖的寬度 width: types.Optional[str] = None, # 詞雲圖的高度 height: types.Optional[str] = None, # 允許詞雲圖的資料展示在畫布範圍之外 is_draw_out_of_bound: bool = False, # 提示框元件配置項,參考 `series_options.TooltipOpts` tooltip_opts: Union[opts.TooltipOpts, dict, None] = None, # 詞雲圖文字的配置 textstyle_opts: types.TextStyle = None, # 詞雲圖文字陰影的範圍 emphasis_shadow_blur: types.Optional[types.Numeric] = None, # 詞雲圖文字陰影的顏色 emphasis_shadow_color: types.Optional[str] = None, ``` 和其他視覺化庫不一樣,pyecharts支援鏈式呼叫。 也就是說新增圖表元素、修改圖表配置,只需要簡單的呼叫元件即可。 下面來個示例: ```python # 匯入WordCloud及配置模組 from pyecharts import options as opts from pyecharts.charts import WordCloud from pyecharts.globals import SymbolType # 新增詞頻資料 words = [ ("Sam S Club", 10000), ("Macys", 6181), ("Amy Schumer", 4386), ("Jurassic World", 4055), ("Charter Communications", 2467), ("Chick Fil A", 2244), ("Planet Fitness", 1868), ("Pitch Perfect", 1484), ("Express", 1112), ("Home", 865), ("Johnny Depp", 847), ("Lena Dunham", 582), ("Lewis Hamilton", 555), ("KXAN", 550), ("Mary Ellen Mark", 462), ("Farrah Abraham", 366), ("Rita Ora", 360), ("Serena Williams", 282), ("NCAA baseball tournament", 273), ("Point Break", 265), ] # WordCloud模組,鏈式呼叫配置,最終生成html檔案 c = ( WordCloud() .add("", words, word_size_range=[20, 100], shape=SymbolType.DIAMOND) .set_global_opts(title_opts=opts.TitleOpts(title="WordCloud-shape-diamond")) .render("wordcloud_diamond.html") ) ``` 生成詞雲圖: ![](https://upload-images.jianshu.io/upload_images/13723999-132300db19408268.gif?imageMogr2/auto-orient/strip) ## 三、商品評論詞雲圖 為了更好地展示pyecharts的詞雲視覺化效果,我找了淘寶商品評論資料集,更貼近應用場景。 程式碼的流程主要是:**資料載入、分詞處理、詞頻統計、詞雲展示**。 ### 1、資料載入 資料集共有10 個商品類別(書籍、平板、手機、水果、洗髮水、熱水器、蒙牛、衣服、計算機、酒店)。 ![](https://upload-images.jianshu.io/upload_images/13723999-f86273322f8484dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ![](https://upload-images.jianshu.io/upload_images/13723999-eda329267e7aa0ed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 共 6 萬多條評論資料,正、負向評論各約 3 萬條。 我們要用的就是欄位review評論資料,程式碼分模組實現不同功能。 首先匯入相關庫: ```python import pandas as pd import jieba from collections import Counter import pyecharts.options as opts from pyecharts.charts import WordCloud ``` 接著載入資料,提取文字: ```python def get_text(goods,evaluation): if evaluation == '好評': evaluation = 1 else: evaluation = 0 path = 'comments.csv' with open(path,encoding='utf-8') as f: data = pd.read_csv(f) # 商品種類 types = data['cat'].unique() # 獲取文字 text = data[(data['cat']==goods)&(data['label']==evaluation)]['review'].values.tolist() text = str(text)[1:-1] print(types) return text ``` ### 2、分詞處理 因為評論資料是一段段完整的話,所以要進行詞雲展示的話肯定得先分詞。 這裡用的分詞庫是jieba,而且添加了停用詞庫,目的是去除符號、副詞等無意義詞彙。 ```python def split_word(text): word_list = list(jieba.cut(text)) # 去掉一些無意義的詞和符號,我這裡自己整理了停用詞庫 with open('停用詞庫.txt') as f: meaningless_word = f.read().splitlines() # print(meaningless_word) result = [] # 篩選詞語 for i in word_list: if i not in meaningless_word: result.append(i.replace(' ', '')) return result ``` ### 3、詞頻統計 分完詞後,需要對詞進行頻數統計,這裡用到collection模組的Counter方法。 然後篩選出詞頻數排名前1000的詞彙,你也可以自行調整。 ```python def word_counter(words): # 詞頻統計,使用Count計數方法 words_counter = Counter(words) # 將Counter型別轉換為列表 words_list = words_counter.most_common(2000) return words_list ``` ### 4、詞雲展示 最後一步使用wordcloud模組對整理好的資料進行視覺化展示。 ```python def word_cloud(data): ( WordCloud() .add(series_name="熱點分析", # 新增資料 data_pair=data, # 字間隙 word_gap = 5, # 調整字大小範圍 word_size_range=[15, 80], shape="cursive", # 選擇背景圖,也可以不加該引數,使用預設背景 mask_image='購物車.jpg') .set_global_opts( title_opts=opts.TitleOpts( title="熱點分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23) ), tooltip_opts=opts.TooltipOpts(is_show=True), ) # 輸出為html格式 .render("basic.html") ) ``` 上面程式碼裡的背景圖可以自己選擇,最好是大輪廓的圖,因為細節展示不出來。 幾個處理函式都寫好了,下面來執行結果: ```python def main(goods,evaluation): text = get_text(goods,evaluation) words = split_word(text) data = word_counter(words) word_cloud(data) if __name__ == '__main__': # 商品種類:書籍、平板、手機、水果、洗髮水、熱水器、衣服、計算機、酒店 # 評論種類:好評、差評 main('手機','好評') ``` 提醒一下,main函式的兩個引數,分別是商品型別和評價型別,你可以自定義組合,然後就會生成該組合的詞雲圖。 用購物車背景圖展示`手機+好評`組合的詞雲圖: ![](https://upload-images.jianshu.io/upload_images/13723999-26d51da56e917d8c.gif?imageMogr2/auto-orient/strip) 用淘寶背景圖展示`計算機+好評`組合的背景圖: ![](https://upload-images.jianshu.io/upload_images/13723999-90c166bc97855090.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 用浴缸背景圖展示`酒店+差評`組合的背景圖: ![](https://upload-images.jianshu.io/upload_images/13723999-9c9879bea1290873.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 用書本背景圖展示`書籍+好評`組合的背景圖: ![](https://upload-images.jianshu.io/upload_images/13723999-3d4c1135a7d34223.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## 四、結論 這裡的展示僅僅為了教大家如何去使用pyecharts製作詞雲,真正的商業用途上需要更加清晰簡潔的表達,在設計層面也要更多的