python?爬取豆瓣電影短評(píng)并利用wordcloud生成詞云圖
前言
最近學(xué)到數(shù)據(jù)可視化到了詞云圖,正好學(xué)到爬蟲,各種爬網(wǎng)站【實(shí)驗(yàn)名稱】 爬取豆瓣電影《千與千尋》的評(píng)論并生成詞云
- 利用爬蟲獲得電影評(píng)論的文本數(shù)據(jù)
- 處理文本數(shù)據(jù)生成詞云圖
第一步、準(zhǔn)備數(shù)據(jù)
需要登錄豆瓣網(wǎng)站才能夠獲得短評(píng)文本數(shù)據(jù)movie.douban.com/subject/129…
首先獲取cookies,使用爬蟲強(qiáng)大的firefox瀏覽器

將cookies數(shù)據(jù)復(fù)制到cookies.txt文件當(dāng)中備用,
第二步、編寫爬蟲代碼
#coding = utf-8
import requests
import time
import random
from bs4 import BeautifulSoup
abss = 'https://movie.douban.com/subject/1291561/comments'
firstPag_url = 'https://movie.douban.com/subject/1291561/comments?start=20&limit=20&sort=new_score&status=P&percent_type='
url = 'https://movie.douban.com/subject/1291561/comments?start=0&limit=20&sort=new_score&status=P'
header = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
'Connection':'keep-alive'
}
def get_data(html):
# 獲取所需要的頁(yè)面數(shù)據(jù)
soup = BeautifulSoup(html, 'lxml')
comment_list = soup.select('.comment > p')
next_page = soup.select('#paginator > a')[2].get('href')
date_nodes = soup.select('..comment-time')
return comment_list, next_page, date_nodes
def get_cookies(path):
# 獲取cookies
f_cookies = open(path, 'r')
cookies ={}
for line in f_cookies.read().split(';'): # 將Cookies字符串其轉(zhuǎn)換為字典
name ,value = line.strip().split('=', 1)
cookies[name] = value
return cookies
if __name__ == '__main__':
cookies = get_cookies('cookies.txt') # cookies文件保存的前面所述的cookies
html = requests.get(firstPag_url, cookies=cookies,headers=header).content
comment_list, next_page, date_nodes = get_data(html) #首先從第一個(gè)頁(yè)面處理
soup = BeautifulSoup(html, 'lxml')
while (next_page): #不斷的處理接下來的頁(yè)面
print(abss + next_page)
html = requests.get(abss + next_page, cookies=cookies, headers=header).content
comment_list, next_page, date_nodes = get_data(html)
soup = BeautifulSoup(html, 'lxml')
comment_list, next_page,date_nodes = get_data(html)
with open("comments.txt", 'a', encoding='utf-8')as f:
for ind in range(len(comment_list)):
comment = comment_list[ind];
date = date_nodes[ind]
comment = comment.get_text().strip().replace("\n", "")
date= date.get_text().strip()
f.writelines(date+u'\n' +comment + u'\n')
time.sleep(1 + float(random.randint(1, 100)) / 20)每一頁(yè)都會(huì)有20條的短評(píng),所以我們依次遍歷每一頁(yè)a

第二步,處理爬到的數(shù)據(jù),在第一步當(dāng)中已經(jīng)將數(shù)據(jù)存檔到了commit.txt文件當(dāng)中,

# -*- coding:utf-8 -*-
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
from scipy.misc import imread
f_comment = open("comments.txt",'rb')
words = []
for line in f_comment.readlines():
if(len(line))==12:
continue
A = jieba.cut(line)
words.append(" ".join(A))
# 去除停用詞
stopwords = [',','。','【','】', '”','“',',','《','》','!','、','?','.','…','1','2','3','4','5','[',']','(',')',' ']
new_words = []
for sent in words :
word_in = sent.split(' ')
new_word_in = []
for word in word_in:
if word in stopwords:
continue
else:
new_word_in.append(word)
new_sent = " ".join(new_word_in)
new_words.append(new_sent)
final_words = []
for sent in new_words:
sent = sent.split(' ')
final_words +=sent
final_words_flt = []
for word in final_words:
if word == ' ':
continue
else:
final_words_flt.append(word)
text = " ".join(final_words_flt)處理完數(shù)據(jù)之后得到帶有空格的高頻詞:

第三步、生成詞云圖
首先安裝python的wordcloud庫(kù):
pip install wordcloud

在第二步text后面加上下面代碼生成詞云圖
font = r'C:\Windows\Fonts\FZSTK.TTF'
bk = imread("bg.png") # 設(shè)置背景文件
wc = WordCloud(collocations=False, mask = bk, font_path=font, width=1400, height=1400, margin=2).generate(text.lower())
image_colors = ImageColorGenerator(bk) # 讀取背景文件色彩
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off")
plt.figure()
plt.imshow(bk, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
wc.to_file('word_cloud1.png') wordcloud作為對(duì)象是為小寫,生成一個(gè)詞云文件大概需要三步:
- 配置詞云對(duì)象參數(shù)
- 加載詞文本
- 輸出詞云文件(如果不加說明默認(rèn)圖片大小是400*200
| 方法 | 描述 |
|---|---|
| Wordcloud.generate(text) | 向wordcloud對(duì)象中加載文本text,例如:wordcloud.genertae(“python && wordclooud”) |
| Wordcloud.to_file(filename) | 將詞云輸出為圖像元件以.png .jpg格式保存,例wordcloud.to_file(“picture.png”) |
具體的方法上面
wordcloud做詞頻統(tǒng)計(jì)時(shí)分為下面幾步:
- 分割:以空格分割單詞
- 統(tǒng)計(jì):單詞出現(xiàn)的次數(shù)并過濾
- 字體:根據(jù)統(tǒng)計(jì)搭配相應(yīng)的字號(hào)
布局:

最后我么可以看到短評(píng)當(dāng)中處理過后的高頻詞

我們隨便照一張圖片讀取背景顏色

最后生成的詞云圖就出來了:

到此這篇關(guān)于python 爬取豆瓣電影短評(píng)并利用wordcloud生成詞云圖的文章就介紹到這了,更多相關(guān)python wordcloud詞云圖內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3+selenium獲取頁(yè)面加載的所有靜態(tài)資源文件鏈接操作
這篇文章主要介紹了python3+selenium獲取頁(yè)面加載的所有靜態(tài)資源文件鏈接操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05
Python模擬登陸淘寶并統(tǒng)計(jì)淘寶消費(fèi)情況的代碼實(shí)例分享
借助urllib、urllib2和BeautifulSoup等幾個(gè)模塊的常用爬蟲開發(fā)組合,我們能夠輕易實(shí)現(xiàn)一份淘寶對(duì)賬單,這里我們就來看一則Python模擬登陸淘寶并統(tǒng)計(jì)淘寶消費(fèi)情況的代碼實(shí)例分享:2016-07-07
用python寫PDF轉(zhuǎn)換器的實(shí)現(xiàn)
這篇文章主要介紹了用python寫PDF轉(zhuǎn)換器的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
對(duì)python requests的content和text方法的區(qū)別詳解
今天小編就為大家分享一篇對(duì)python requests的content和text方法的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
python使用線程封裝的一個(gè)簡(jiǎn)單定時(shí)器類實(shí)例
這篇文章主要介紹了python使用線程封裝的一個(gè)簡(jiǎn)單定時(shí)器類,實(shí)例分析了Python線程的使用及定時(shí)器類的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-05-05

