經(jīng)常有朋友問怎么使用Python繪制詞云圖给猾?今天我們展示一個簡單的demo,有興趣的朋友可以嘗試跟著DIY哦~
1. 前期準(zhǔn)備
在繪制詞云圖之前颂跨,我們要先安裝所需的第三方庫敢伸。
- 安裝jieba:
conda install -c conda-forge jieba
- 安裝wordcloud:
conda install -c conda-forge wordcloud
2. 準(zhǔn)備需要分析的內(nèi)容
這里你可以直接使用你已經(jīng)準(zhǔn)備好的內(nèi)容,在這個demo中恒削,我們通過獲取pubmed上以lung cancer為關(guān)鍵詞搜索的前10頁的文章題目作為分析的內(nèi)容池颈。這里我們采用requests獲取網(wǎng)頁信息尾序,然后使用beautiful soup進(jìn)行網(wǎng)頁結(jié)構(gòu)分析。
import re
import jieba
import jieba.analyse
import codecs
import wordcloud
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
page = 10 # 設(shè)置獲取前10頁的內(nèi)容
start_url = ('https://pubmed.ncbi.nlm.nih.gov/?term=lung+cancer') # 設(shè)置搜索網(wǎng)址與關(guān)鍵詞lung cancer
# 循換10頁內(nèi)容躯砰,獲取頁面所有文章的題目
all_content = ''
for i in range(int(page)):
url = start_url + "&page=" + str(int(i)+1)
#爬取網(wǎng)頁
r = requests.get(url, headers= {'user-agent':'Mozilla/5.0'})
r.raise_for_status()
r.encoding = r.apparent_encoding
html = r.text
#提取題目信息
soup = BeautifulSoup(html, 'html.parser')
for paper in soup.find_all(attrs={'class':'docsum-content'}):
name = str(paper.a).split('">')[1]
title = re.sub(r'(</a>|<b>|</b>)', '', name).strip()
all_content += title + '\n'
with open('title.txt', 'a', encoding='utf-8') as out_file:
out_file.write(title.lower() + '\n')
3. 詞頻統(tǒng)計
在我們進(jìn)行詞頻統(tǒng)計之前每币,我們還需要做一些準(zhǔn)備工作。
在這個簡單的demo中琢歇,我們處理的內(nèi)容是全英文的兰怠,大家都知道英文單詞之間是以空格來間隔的,所以對計算機(jī)很友好李茫,它可以很容易識別出每個英文單詞揭保。但是,我們要知道魄宏,我們的中文的詞組間是沒有空格間隔的秸侣。所有,大家要注意如果你要處理的內(nèi)容是中文的宠互,你需要先進(jìn)行中文分詞處理味榛,中文分詞就是要告訴計算機(jī)哪些內(nèi)容是一個詞組。比如名秀,“我是學(xué)生”這句話励负,通過分詞處理就變成了“我 | 是 | 學(xué)生”。如果大家有中文分詞的需求匕得,可以進(jìn)一步參考jiba官方文檔继榆。
接著,我們要剔除停用詞(stop words)汁掠。什么是停用詞呢略吨?簡單的說,就是處理詞頻的時候我們不需要統(tǒng)計的的詞匯考阱,字符翠忠。比如英文中的“a,an,and,or...”;又比如中文中的“的乞榨、地秽之、了...”。
在這個例子中吃既,我們通過統(tǒng)計考榨,篩選了出現(xiàn)頻率最高的前100個單詞進(jìn)行下一步詞云圖的繪制。
#載入停用詞數(shù)據(jù)
stopwords = [line.strip() for line in codecs.open('stopwords.txt', 'r', 'utf-8').readlines()]
#詞頻統(tǒng)計
segments = {}
words = jieba.cut(all_content)
for word in words:
if word not in stopwords:
segments[word] = segments.get(word, 0) + 1
#按照詞頻排序
sort_segments = sorted(segments.items(), key=lambda item:item[1], reverse=True)
words_on_list = []
for word, count in sort_segments[:99]:
words_on_list.append(word)
4. 繪制詞云圖
使用wordcloud繪制詞云圖鹦倚,然后使用matplotlib實現(xiàn)圖片的顯示與題目的設(shè)置河质。
#生成詞云
word_show = ' '.join(words_on_list)
w = wordcloud.WordCloud(font_path="msyh.ttc", width=1000, height= 700,background_color="white", max_words=100)
w.generate(word_show)
w.to_file("hot_word.jpg")
plt.figure(figsize=(8,8.5))
plt.imshow(w, interpolation='bilinear')
plt.axis('off')
plt.title('Most Popular Words in Title', fontsize=30)
plt.show()
最后就得到了我們想要的詞云圖: