python爬蟲:詞雲分析最熱門電影《後來的我們》

 

跟閨蜜週末去看了電影《後來的我們》,被感動的一塌糊塗,回來後心血來潮,寫了這麼個詞雲分析工具~

1 模塊庫使用說明
1.1 requests庫
requests 是用Python語言編寫,基於 urllib,採用 Apache2 Licensed 開源協議的 HTTP 庫。它比 urllib 更加方便,可以節約我們大量的工作,完全滿足 HTTP 測試需求。
1.2 urllib庫
urllib的request模塊可以非常方便地抓取URL內容,也就是發送一個GET請求到指定的頁面,然後返回HTTP的響應.
1.3jieba庫

結巴”中文分詞:做最好的 Python 中文分詞組件

1.4 BeautifulSoup庫
   Beautiful Soup是用Python寫的一個HTML/XML的解析器,它可以很好的處理不規範標記並生成剖析樹(parse tree)。 它提供簡單又常用的導航navigating,搜索以及修改剖析樹的操作。
1.5pandas庫

pandas是python的一個非常強大的數據分析庫,常用於數據分析。
1.6 re庫
正則表達式re(通項公式)是用來簡潔表達一組字符串的表達式。優勢是簡潔。使用它來進行字符串處理。
1.7 wordcloud庫
python中使用wordcloud包生成的詞雲圖。我們最後要生成當前熱映電影的分析詞雲。
2需求說明
介紹要做什麼,將採用的方法、預期得到的結果是什麼及其他需求說明。
爬取豆瓣網站https://movie.douban.com/cinema/nowplaying/ankang/ 城市爲安康的豆瓣電影數據主要完成以下三個步驟
抓取網頁數據
清理數據
用詞雲進行展示
使用的python版本是3.6.並使用中文分詞,詞雲對豆瓣電影排行榜排行第一的電影進行數據分析,進行相應的詞雲展示。

3抓取和處理數據算法

1)安裝request模塊

1.1)安裝需要用到的beautifulsoup模塊

2)查看要爬取網站的結構

3)初步代碼實現

3.1)初步爬取到當前的院線上映信息

4.1)抓取到熱映電影的第一個熱評信息代碼

4.2)成功顯示熱評信息

5.1)進行數據清洗上一步中格式錯亂的代碼

5.2)數據清洗後的《後來的我們》評論信息

5.3)再次進行數據清洗去除掉標點符號代碼

5.4)去除掉標點符號後的數據

6.1)安裝pandas模塊 ,用此方法依次安裝wordcloud 庫等。

def main():
    # 循環獲取第一個電影的前10頁評論
    commentList = []
    NowPlayingMovie_list = getNowPlayingMovie_list()
    for i in range(10):
        num = i + 1
        commentList_temp = getCommentsById(NowPlayingMovie_list[0]['id'], num)
        commentList.append(commentList_temp)

使用for語句循環遍歷獲取排行榜第一的電影的前十頁評論

完整代碼:

# coding:utf-8
__author__ = 'LiuYang'

import warnings

warnings.filterwarnings("ignore")
import jieba  # 分詞包
import numpy  # numpy計算包
import codecs  # codecs提供的open方法來指定打開的文件的語言編碼,它會在讀取的時候自動轉換爲內部unicode
import re
import pandas as pd
import matplotlib.pyplot as plt
from urllib import request
from bs4 import BeautifulSoup as bs


import matplotlib

matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
from wordcloud import WordCloud  # 詞雲包


# 分析網頁函數
def getNowPlayingMovie_list():
    resp = request.urlopen('https://movie.douban.com/nowplaying/ankang/')  # 爬取安康地區的豆瓣電影信息
    html_data = resp.read().decode('utf-8')
    soup = bs(html_data, 'html.parser')
    nowplaying_movie = soup.find_all('div', id='nowplaying')
    nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')
    nowplaying_list = []
    for item in nowplaying_movie_list:
        nowplaying_dict = {}
        nowplaying_dict['id'] = item['data-subject']
        for tag_img_item in item.find_all('img'):
            nowplaying_dict['name'] = tag_img_item['alt']
            nowplaying_list.append(nowplaying_dict)
    return nowplaying_list


# 爬取評論函數
def getCommentsById(movieId, pageNum):
    eachCommentList = [];
    if pageNum > 0:
        start = (pageNum - 1) * 20
    else:
        return False
    requrl = 'https://movie.douban.com/subject/' + movieId + '/comments' + '?' + 'start=' + str(start) + '&limit=20'
    print(requrl)
    resp = request.urlopen(requrl)
    html_data = resp.read().decode('utf-8')
    soup = bs(html_data, 'html.parser')
    comment_div_lits = soup.find_all('div', class_='comment')
    for item in comment_div_lits:
        if item.find_all('p')[0].string is not None:
            eachCommentList.append(item.find_all('p')[0].string)
    return eachCommentList


def main():
    # 循環獲取第一個電影的前10頁評論
    commentList = []
    NowPlayingMovie_list = getNowPlayingMovie_list()
    for i in range(10):
        num = i + 1
        commentList_temp = getCommentsById(NowPlayingMovie_list[0]['id'], num)
        commentList.append(commentList_temp)

    # 將列表中的數據轉換爲字符串
    comments = ''
    for k in range(len(commentList)):
        comments = comments + (str(commentList[k])).strip()

    # 使用正則表達式去除標點符號
    pattern = re.compile(r'[\u4e00-\u9fa5]+')
    filterdata = re.findall(pattern, comments)
    cleaned_comments = ''.join(filterdata)

    # 使用結巴分詞進行中文分詞
    segment = jieba.lcut(cleaned_comments)
    words_df = pd.DataFrame({'segment': segment})

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

    # 統計詞頻
    words_stat = words_df.groupby(by=['segment'])['segment'].agg({"計數": numpy.size})
    words_stat = words_stat.reset_index().sort_values(by=["計數"], ascending=False)

    # 用詞雲進行顯示
    wordcloud = WordCloud(font_path="simhei.ttf", background_color="white", max_font_size=80)
    word_frequence = {x[0]: x[1] for x in words_stat.head(1000).values}

    word_frequence_list = []
    for key in word_frequence:
        temp = (key, word_frequence[key])
        word_frequence_list.append(temp)

    wordcloud = wordcloud.fit_words(dict (word_frequence_list))
    plt.imshow(wordcloud)
    plt.savefig("ciyun_jieguo .jpg")

# 主函數
main()

成功獲取到結果

到代碼路徑獲取詞雲結果圖片如圖:

詞雲結果圖

4結果分析說明
選取安康地區院線電影排行信息,首先對正在上映的電影進行分析,獲得最熱門的電影信息,第二步對排行中最熱門的電影《後來的我們》進行評論抓取,進行數據清洗,去除掉格式錯誤的錯誤信息,去除掉標點,中文的疊詞,獲取到出現頻率最高的詞彙,爲了保證獲取到的詞雲信息準確性,並且循環遍歷十頁評論信息,統計計數,再通過詞雲獲取到此電影的詞雲信息。
由最終獲得的詞雲分析圖可知,我們順利的爬取了安康地區的豆瓣電影信息,影院當前正在上映的電影信息,由此得到熱門電影《後來的我們》此電影的特徵標籤,也基本上反映了這部電影的情況,觀影者的感受,電影的主要角色,導演信息等一目瞭然。

掃描下方二維碼關注微信公衆號「南城故夢」,一個程序猿的後花園

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章