楼主: ReneeBK
4259 33

Python 爬虫实践:《战狼2》豆瓣影评分析 [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4896份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49634 个
通用积分
55.5065
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2017-8-27 05:24:51 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
摘要: 刚接触python不久,做一个小项目来练练手。前几天看了《战狼2》,发现它在最新上映的电影里面是排行第一的,如下图所示。准备把豆瓣上对它的影评做一个分析。第一个参数为需要提取数据的html,第二个参数是指定解析 ...


本帖隐藏的内容

Python 爬虫实践:《战狼2》豆瓣影评分析.pdf (2.13 MB)


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:python hide HTML HID IDE

沙发
ReneeBK 发表于 2017-8-27 05:25:28
  1. #coding:utf-8
  2. __author__ = 'hang'

  3. import warnings
  4. warnings.filterwarnings("ignore")
  5. import jieba    #分词包
  6. import numpy    #numpy计算包
  7. import codecs   #codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
  8. import re
  9. import pandas as pd  
  10. import matplotlib.pyplot as plt
  11. from urllib import request
  12. from bs4 import BeautifulSoup as bs
  13. %matplotlib inline

  14. import matplotlib
  15. matplotlib.rcParams['figure.figsize'] = (10.0, 5.0)
  16. from wordcloud import WordCloud#词云包

  17. #分析网页函数
  18. def getNowPlayingMovie_list():   
  19.     resp = request.urlopen('https://movie.douban.com/nowplaying/hangzhou/')        
  20.     html_data = resp.read().decode('utf-8')   
  21.     soup = bs(html_data, 'html.parser')   
  22.     nowplaying_movie = soup.find_all('div', id='nowplaying')        
  23.     nowplaying_movie_list = nowplaying_movie[0].find_all('li', class_='list-item')   
  24.     nowplaying_list = []   
  25.     for item in nowplaying_movie_list:        
  26.         nowplaying_dict = {}        
  27.         nowplaying_dict['id'] = item['data-subject']      
  28.         for tag_img_item in item.find_all('img'):            
  29.             nowplaying_dict['name'] = tag_img_item['alt']            
  30.             nowplaying_list.append(nowplaying_dict)   
  31.     return nowplaying_list

  32. #爬取评论函数
  33. def getCommentsById(movieId, pageNum):
  34.     eachCommentList = [];
  35.     if pageNum>0:
  36.          start = (pageNum-1) * 20
  37.     else:
  38.         return False
  39.     requrl = 'https://movie.douban.com/subject/' + movieId + '/comments' +'?' +'start=' + str(start) + '&limit=20'
  40.     print(requrl)
  41.     resp = request.urlopen(requrl)
  42.     html_data = resp.read().decode('utf-8')
  43.     soup = bs(html_data, 'html.parser')
  44.     comment_div_lits = soup.find_all('div', class_='comment')
  45.     for item in comment_div_lits:
  46.         if item.find_all('p')[0].string is not None:     
  47.             eachCommentList.append(item.find_all('p')[0].string)
  48.     return eachCommentList

  49. def main():
  50.     #循环获取第一个电影的前10页评论
  51.     commentList = []
  52.     NowPlayingMovie_list = getNowPlayingMovie_list()
  53.     for i in range(10):   
  54.         num = i + 1
  55.         commentList_temp = getCommentsById(NowPlayingMovie_list[0]['id'], num)
  56.         commentList.append(commentList_temp)

  57.     #将列表中的数据转换为字符串
  58.     comments = ''
  59.     for k in range(len(commentList)):
  60.         comments = comments + (str(commentList[k])).strip()

  61.     #使用正则表达式去除标点符号
  62.     pattern = re.compile(r'[\u4e00-\u9fa5]+')
  63.     filterdata = re.findall(pattern, comments)
  64.     cleaned_comments = ''.join(filterdata)

  65.     #使用结巴分词进行中文分词
  66.     segment = jieba.lcut(cleaned_comments)
  67.     words_df=pd.DataFrame({'segment':segment})

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

  71.     #统计词频
  72.     words_stat=words_df.groupby(by=['segment'])['segment'].agg({"计数":numpy.size})
  73.     words_stat=words_stat.reset_index().sort_values(by=["计数"],ascending=False)

  74.     #用词云进行显示
  75.     wordcloud=WordCloud(font_path="simhei.ttf",background_color="white",max_font_size=80)
  76.     word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}

  77.     word_frequence_list = []
  78.     for key in word_frequence:
  79.         temp = (key,word_frequence[key])
  80.         word_frequence_list.append(temp)

  81.     wordcloud=wordcloud.fit_words(word_frequence_list)
  82.     plt.imshow(wordcloud)

  83. #主函数
  84. main()
复制代码

藤椅
陈信研究员 发表于 2017-8-27 06:08:06
不错的体验
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

板凳
vacant123 发表于 2017-8-27 06:30:05
6666666666666666
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

报纸
vacant123 发表于 2017-8-27 06:33:14
6666666666666666

地板
MouJack007 发表于 2017-8-27 11:50:02
谢谢楼主分享!
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

7
MouJack007 发表于 2017-8-27 11:50:28

8
cszcszcsz 发表于 2017-8-27 13:57:11
谢谢分享!

9
mumutang 学生认证  发表于 2017-8-27 14:03:29
66666666666
已有 1 人评分论坛币 收起 理由
Nicolle + 20 热心帮助其他会员

总评分: 论坛币 + 20   查看全部评分

10
钱学森64 发表于 2017-8-27 15:22:54
谢谢分享
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-9 07:21