自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python爬蟲實踐:《戰(zhàn)狼2》豆瓣影評分析

開發(fā) 后端
剛接觸python不久,做一個小項目來練練手。前幾天看了《戰(zhàn)狼2》,發(fā)現(xiàn)它在最新上映的電影里面是排行第一的,如下圖所示。準備把豆瓣上對它的影評做一個分析。

簡介

剛接觸python不久,做一個小項目來練練手。前幾天看了《戰(zhàn)狼2》,發(fā)現(xiàn)它在***上映的電影里面是排行***的,如下圖所示。準備把豆瓣上對它的影評做一個分析。

目標總覽

主要做了三件事:

  • 抓取網(wǎng)頁數(shù)據(jù)
  • 清理數(shù)據(jù)
  • 用詞云進行展示

使用的python版本是3.5.

一、抓取網(wǎng)頁數(shù)據(jù)

***步要對網(wǎng)頁進行訪問,python中使用的是urllib庫。代碼如下: 

  1. from urllib import request  
  2. resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/' 
  3. html_data = resp.read().decode('utf-8'

其中https://movie.douban.com/nowplaying/hangzhou/是豆瓣***上映的電影頁面,可以在瀏覽器中輸入該網(wǎng)址進行查看。

html_data是字符串類型的變量,里面存放了網(wǎng)頁的html代碼。

輸入print(html_data)可以查看,如下圖所示:

第二步,需要對得到的html代碼進行解析,得到里面提取我們需要的數(shù)據(jù)。

在python中使用BeautifulSoup庫進行html代碼的解析。

(注:如果沒有安裝此庫,則使用pip install BeautifulSoup進行安裝即可?。?/p>

BeautifulSoup使用的格式如下:

  1. BeautifulSoup(html,"html.parser"

***個參數(shù)為需要提取數(shù)據(jù)的html,第二個參數(shù)是指定解析器,然后使用find_all()讀取html標簽中的內(nèi)容。

但是html中有這么多的標簽,該讀取哪些標簽?zāi)??其實,最簡單的辦法是我們可以打開我們爬取網(wǎng)頁的html代碼,然后查看我們需要的數(shù)據(jù)在哪個html標簽里面,再進行讀取就可以了。如下圖所示:

從上圖中可以看出在div id=”nowplaying“標簽開始是我們想要的數(shù)據(jù),里面有電影的名稱、評分、主演等信息。所以相應(yīng)的代碼編寫如下: 

  1. from bs4 import BeautifulSoup as bs 
  2. soup = bs(html_data, 'html.parser')     
  3. nowplaying_movie = soup.find_all('div', id='nowplaying'
  4. nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item'

其中nowplaying_movie_list 是一個列表,可以用print(nowplaying_movie_list[0])查看里面的內(nèi)容,如下圖所示:

在上圖中可以看到data-subject屬性里面放了電影的id號碼,而在img標簽的alt屬性里面放了電影的名字,因此我們就通過這兩個屬性來得到電影的id和名稱。(注:打開電影短評的網(wǎng)頁時需要用到電影的id,所以需要對它進行解析),編寫代碼如下: 

  1. nowplaying_list = []  
  2. for item in nowplaying_movie_list:     
  3.         nowplaying_dict = {}    
  4.         nowplaying_dict['id'] = item['data-subject'
  5.         for tag_img_item in item.find_all('img'):   
  6.             nowplaying_dict['name'] = tag_img_item['alt']  
  7.             nowplaying_list.append(nowplaying_dict) 

其中列表nowplaying_list中就存放了***電影的id和名稱,可以使用print(nowplaying_list)進行查看,如下圖所示:

可以看到和豆瓣網(wǎng)址上面是匹配的。這樣就得到了***電影的信息了。接下來就要進行對***電影短評進行分析了。例如《戰(zhàn)狼2》的短評網(wǎng)址為:https://movie.douban.com/subject/26363254/comments?start=0&limit=20

其中26363254就是電影的id,start=0表示評論的第0條評論。

接下來接對該網(wǎng)址進行解析了。打開上圖中的短評頁面的html代碼,我們發(fā)現(xiàn)關(guān)于評論的數(shù)據(jù)是在div標簽的comment屬性下面,如下圖所示:

因此對此標簽進行解析,代碼如下: 

  1. requrl = 'https://movie.douban.com/subject/' + nowplaying_list[0]['id'] + '/comments' +'?' +'start=0' + '&limit=20' 
  2. resp = request.urlopen(requrl) 
  3. html_data = resp.read().decode('utf-8'
  4. soup = bs(html_data, 'html.parser'
  5. comment_div_lits = soup.find_all('div', class_='comment'

此時在comment_div_lits 列表中存放的就是div標簽和comment屬性下面的html代碼了。在上圖中還可以發(fā)現(xiàn)在p標簽下面存放了網(wǎng)友對電影的評論,如下圖所示:

因此對comment_div_lits 代碼中的html代碼繼續(xù)進行解析,代碼如下: 

  1. eachCommentList = [];  
  2. for item in comment_div_lits:   
  3.         if item.find_all('p')[0].string is not None:    
  4.             eachCommentList.append(item.find_all('p')[0].string) 

使用print(eachCommentList)查看eachCommentList列表中的內(nèi)容,可以看到里面存里我們想要的影評。如下圖所示:

好的,至此我們已經(jīng)爬取了豆瓣最近播放電影的評論數(shù)據(jù),接下來就要對數(shù)據(jù)進行清洗和詞云顯示了。

二、數(shù)據(jù)清洗

為了方便進行數(shù)據(jù)進行清洗,我們將列表中的數(shù)據(jù)放在一個字符串數(shù)組中,代碼如下: 

  1. comments = ''  
  2. for k in range(len(eachCommentList)):  
  3.     comments = comments + (str(eachCommentList[k])).strip() 

使用print(comments)進行查看,如下圖所示:

可以看到所有的評論已經(jīng)變成一個字符串了,但是我們發(fā)現(xiàn)評論中還有不少的標點符號等。這些符號對我們進行詞頻統(tǒng)計時根本沒有用,因此要將它們清除。所用的方法是正則表達式。python中正則表達式是通過re模塊來實現(xiàn)的。代碼如下: 

  1. import re   
  2. pattern = re.compile(r'[\u4e00-\u9fa5]+' 
  3. filterdata = re.findall(pattern, comments)  
  4. cleaned_comments = ''.join(filterdata) 

繼續(xù)使用print(cleaned_comments)語句進行查看,如下圖所示:

我們可以看到此時評論數(shù)據(jù)中已經(jīng)沒有那些標點符號了,數(shù)據(jù)變得“干凈”了很多。

因此要進行詞頻統(tǒng)計,所以先要進行中文分詞操作。在這里我使用的是結(jié)巴分詞。如果沒有安裝結(jié)巴分詞,可以在控制臺使用pip install jieba進行安裝。(注:可以使用pip list查看是否安裝了這些庫)。代碼如下所示: 

  1. import jieba    #分詞包  
  2. import pandas as pd     
  3. segment = jieba.lcut(cleaned_comments)  
  4. words_df=pd.DataFrame({'segment':segment}) 

因為結(jié)巴分詞要用到pandas,所以我們這里加載了pandas包??梢允褂脀ords_df.head()查看分詞之后的結(jié)果,如下圖所示:

從上圖可以看到我們的數(shù)據(jù)中有“看”、“太”、“的”等虛詞(停用詞),而這些詞在任何場景中都是高頻時,并且沒有實際的含義,所以我們要他們進行清除。

我把停用詞放在一個stopwords.txt文件中,將我們的數(shù)據(jù)與停用詞進行比對即可(注:只要在百度中輸入stopwords.txt,就可以下載到該文件)。去停用詞代碼如下代碼如下: 

  1. stopwords=pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用  
  2. words_df=words_df[~words_df.segment.isin(stopwords.stopword)] 

繼續(xù)使用words_df.head()語句來查看結(jié)果,如下圖所示,停用詞已經(jīng)被出去了。

接下來就要進行詞頻統(tǒng)計了,代碼如下: 

  1. import numpy    #numpy計算包  
  2. words_stat=words_df.groupby(by=['segment'])['segment'].agg({"計數(shù)":numpy.size})  
  3. words_stat=words_stat.reset_index().sort_values(by=["計數(shù)"],ascending=False

用words_stat.head()進行查看,結(jié)果如下:

由于我們前面只是爬取了***頁的評論,所以數(shù)據(jù)有點少,在***給出的完整代碼中,我爬取了10頁的評論,所數(shù)據(jù)還是有參考價值。

三、用詞云進行顯示

代碼如下: 

  1. import matplotlib.pyplot as plt  
  2. %matplotlib inline   
  3.  
  4. import matplotlib  
  5. matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)  
  6. from wordcloud import WordCloud#詞云包    
  7. wordcloud=WordCloud(font_path="simhei.ttf",background_color="white",max_font_size=80) #指定字體類型、字體大小和字體顏色  
  8. word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values 
  9. word_frequence_list = []  
  10. for key in word_frequence:  
  11.     temp = (key,word_frequence[key])  
  12.     word_frequence_list.append(temp  
  13.  
  14. wordcloud=wordcloud.fit_words(word_frequence_list)  
  15. plt.imshow(wordcloud) 

其中simhei.ttf使用來指定字體的,可以在百度上輸入simhei.ttf進行下載后,放入程序的根目錄即可。顯示的圖像如下:

到此為止,整個項目的介紹就結(jié)束了。由于自己也還是個初學(xué)者,接觸python不久,代碼寫的并不好。而且***次寫技術(shù)博客,表達的有些冗余,請大家多多包涵,有不對的地方,請大家批評指正。以后我也會將自己做的小項目以這種形式寫在博客上和大家一起交流!***貼上完整的代碼。

完整代碼 

  1. #coding:utf-8  
  2. __author__ = 'hang'   
  3.  
  4. import warnings  
  5. warnings.filterwarnings("ignore" 
  6. import jieba    #分詞包  
  7. import numpy    #numpy計算包  
  8. import codecs   #codecs提供的open方法來指定打開的文件的語言編碼,它會在讀取的時候自動轉(zhuǎn)換為內(nèi)部unicode   
  9. import re  
  10. import pandas as pd    
  11. import matplotlib.pyplot as plt  
  12. from urllib import request  
  13. from bs4 import BeautifulSoup as bs  
  14. %matplotlib inline  
  15. import matplotlib  
  16. matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)  
  17. from wordcloud import WordCloud#詞云包   
  18.  
  19. #分析網(wǎng)頁函數(shù)  
  20. def getNowPlayingMovie_list():    
  21.     resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/')    
  22.     html_data = resp.read().decode('utf-8')     
  23.     soup = bs(html_data, 'html.parser')    
  24.     nowplaying_movie = soup.find_all('div', id='nowplaying')   
  25.     nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')  
  26.     nowplaying_list = []     
  27.     for item in nowplaying_movie_list:  
  28.         nowplaying_dict = {}         
  29.         nowplaying_dict['id'] = item['data-subject'
  30.         for tag_img_item in item.find_all('img'):  
  31.             nowplaying_dict['name'] = tag_img_item['alt']  
  32.             nowplaying_list.append(nowplaying_dict)  
  33.     return nowplaying_list 
  34.   
  35.  
  36. #爬取評論函數(shù)  
  37. def getCommentsById(movieId, pageNum):   
  38.     eachCommentList = [];  
  39.     if pageNum>0:   
  40.          start = (pageNum-1) * 20  
  41.     else:   
  42.         return False  
  43.     requrl = 'https://movie.douban.com/subject/' + movieId + '/comments' +'?' +'start=' + str(start) + '&limit=20'  
  44.     print(requrl)  
  45.     resp = request.urlopen(requrl) 
  46.     html_data = resp.read().decode('utf-8' 
  47.     soup = bs(html_data, 'html.parser' 
  48.     comment_div_lits = soup.find_all('div', class_='comment' 
  49.     for item in comment_div_lits:   
  50.         if item.find_all('p')[0].string is not None:     
  51.             eachCommentList.append(item.find_all('p')[0].string)  
  52.     return eachCommentList   
  53.  
  54. def main():  
  55.     #循環(huán)獲取***個電影的前10頁評論  
  56.     commentList = []  
  57.     NowPlayingMovie_list = getNowPlayingMovie_list()  
  58.     for i in range(10):      
  59.         num = i + 1  
  60.         commentList_temp = getCommentsById(NowPlayingMovie_list[0]['id'], num)  
  61.         commentList.append(commentList_temp)  
  62.   
  63.  
  64.     #將列表中的數(shù)據(jù)轉(zhuǎn)換為字符串  
  65.     comments = ''  
  66.     for k in range(len(commentList)):  
  67.         comments = comments + (str(commentList[k])).strip()   
  68.  
  69.     #使用正則表達式去除標點符號  
  70.     pattern = re.compile(r'[\u4e00-\u9fa5]+' 
  71.     filterdata = re.findall(pattern, comments)  
  72.     cleaned_comments = ''.join(filterdata)   
  73.  
  74.     #使用結(jié)巴分詞進行中文分詞  
  75.     segment = jieba.lcut(cleaned_comments)  
  76.     words_df=pd.DataFrame({'segment':segment})  
  77.   
  78.  
  79.     #去掉停用詞  
  80.     stopwords=pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')#quoting=3全不引用  
  81.     words_df=words_df[~words_df.segment.isin(stopwords.stopword)]  
  82.   
  83.  
  84.     #統(tǒng)計詞頻  
  85.     words_stat=words_df.groupby(by=['segment'])['segment'].agg({"計數(shù)":numpy.size})  
  86.     words_stat=words_stat.reset_index().sort_values(by=["計數(shù)"],ascending=False 
  87.   
  88.  
  89.     #用詞云進行顯示  
  90.     wordcloud=WordCloud(font_path="simhei.ttf",background_color="white",max_font_size=80)  
  91.     word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values 
  92.   
  93.  
  94.     word_frequence_list = []  
  95.     for key in word_frequence:  
  96.         temp = (key,word_frequence[key])  
  97.         word_frequence_list.append(temp 
  98.  
  99.     wordcloud=wordcloud.fit_words(word_frequence_list)  
  100.     plt.imshow(wordcloud)   
  101.  
  102. #主函數(shù)  
  103. main() 

結(jié)果顯示如下:

 

上圖基本反映了《戰(zhàn)狼2》這部電影的情況。 

責(zé)任編輯:龐桂玉 來源: 數(shù)據(jù)分析與開發(fā)
相關(guān)推薦

2017-08-09 09:19:30

2018-08-02 14:12:16

影評分析狄仁杰之四大天王

2017-04-18 20:09:14

數(shù)據(jù)分析電影評分

2017-08-21 10:05:57

Python影評 爬蟲

2018-05-23 12:34:39

Python網(wǎng)絡(luò)爬蟲豆瓣電影

2017-08-17 11:20:02

戰(zhàn)狼

2017-08-10 11:00:35

2024-01-23 08:00:00

區(qū)間評分法電影評分算法

2017-08-10 14:20:50

互聯(lián)網(wǎng)

2017-06-16 21:00:02

Python爬蟲

2013-11-06 11:29:39

PhoneGap

2018-01-11 10:20:04

Python爬蟲豆瓣音樂

2019-05-15 15:57:15

Python數(shù)據(jù)分析爬蟲

2021-03-08 08:21:19

詞云數(shù)據(jù)可視化大數(shù)據(jù)

2019-05-21 14:08:40

豆瓣Python圖書

2011-07-26 09:31:39

Windows Ser

2019-08-27 07:53:41

2018-07-25 13:47:51

彭于晏邪不壓正Python

2018-11-05 16:18:28

數(shù)據(jù)電視劇演員

2015-03-23 17:48:07

button
點贊
收藏

51CTO技術(shù)棧公眾號