python爬取豆瓣評論制作詞云代碼
一、爬取豆瓣熱評
該程序進行爬取豆瓣熱評,將爬取的評論(json文件)保存到與該python文件同一級目錄下
注意需要下載這幾個庫:requests、lxml、json、time
import requests from lxml import etree import json import time class Spider(object): def __init__(self): #seif.ure='https://movie.douban.com/subject/23885074/reviews?start=0' self.headers={ 'User-Agent':'Mozilla/5.0(Windows NT6.1;Win64;x64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/75.0.3700.100Safari/537.36' } def get_data(self,url): response = requests.get(url,headers=self.headers).content.decode('utf-8') page=etree.HTML(response)#xpath 對象 #獲取所有數(shù)據(jù)節(jié)點 node_list = page.xpath('//div[@class="review-list "]/div') for node in node_list: #作者 author = node.xpath('.//header[@class="main-hd"]//a[2]/text()')[0] #評論 text = node.xpath('string(.//div[@class="main-bd"]//div[@class="short-content"])') items={ 'author':author, 'text':text.strip() } #持久化存儲 with open('yewen.json','a',encoding='utf-8') as f: f.write(json.dumps(items,ensure_ascii=False)+'\n') def run(self): for i in range(1,47): url='https://movie.douban.com/subject/26885074/reviews?start{}'.format(i*20) print('正在爬取第{}頁'.format(i)) self.get_data(url) time.sleep(3) if __name__=='__main__': s=Spider() s.run()
二、制作詞云
該程序?qū)son中的數(shù)據(jù)進行處理,提取重要信息,并用wordcloud庫制作詞云圖片,同樣保存到與該python文件同一級目錄下
注意需要下載這幾個庫:jieba、wordcloud、json
import jieba from wordcloud import WordCloud import json f= open("yewen.json", "r", encoding="utf-8") data_list= f.readlines() str ='' for data in data_list: text= json.loads(data)['text'] str +=text #替換無關(guān)緊要的詞語 result_str = str.replace('展開', '').replace('這篇','').replace('影評','').replace('電影','').replace('這部', '').replace('可能', '').replace('劇情','') cut_text = jieba.lcut(result_str) result = " ".join(cut_text) wc = WordCloud(font_path='simhei.ttf', background_color="white", max_words=600, width=1000, height=1000, min_font_size=20, max_font_size=100,) #mast=plt.imreda('snake.jpg')#背景圖片 wc.generate(result)#轉(zhuǎn)化為詞云的操作 wc.to_file("text.jpg")#保存 f.close()
總結(jié)
到此這篇關(guān)于python爬取豆瓣評論制作詞云代碼的文章就介紹到這了,更多相關(guān)python爬取豆瓣評論內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用sys.exc_info()方法獲取異常信息
這篇文章主要介紹了Python使用sys.exc_info()方法獲取異常信息,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07python數(shù)據(jù)結(jié)構(gòu)輸入輸出及控制和異常
這篇文章主要介紹了python數(shù)據(jù)結(jié)構(gòu)輸入輸出及控制和異常,上一章節(jié)中我們介紹了python的基礎(chǔ)數(shù)據(jù)類型和集合數(shù)據(jù)類型,這章節(jié)給大家介紹一下python的輸入輸出、控制和異常,對數(shù)據(jù)類型感興趣的同學可以查看一下文章<BR>2021-12-12Django與圖表的數(shù)據(jù)交互的實現(xiàn)
本文主要介紹了Django與圖表的數(shù)據(jù)交互的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08