鱼C论坛

 找回密码
 立即注册
查看: 1590|回复: 2

[作品展示] 豆瓣Top250数据可视化

[复制链接]
发表于 2022-3-2 17:13:02 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 atrago 于 2022-3-8 18:32 编辑

操作环境:Jupyter Notebook
目的:

1、获取豆瓣网站Top250电影排名数据。
2、根据所得数据获得电影排名分布情况和电影年代分布情况。

实现过程:

1、豆瓣高分电影Top250数据获取并分析评分分布情况和年代分布情况
2、利用bs4、request模块爬取豆瓣电影排行榜数据,对获取的数据利用Numpy模块,Pandas模块,进行数据清洗,Matplotlib模块进行可视化
3、成功得到电影评分分布情况和电影年代分布情况可视化图表


困难及解决方案:
1、获取数据后对数据格式排列没有清洗的概念,不知道如何两个表格数据进行合并;查询利用Numpy模块中的merge函数。
2、可视化标签设置错误;查阅matplotlib.pyplot相关阅读指导进行改正。


改进计划:

1、代码标签有部分乱码现象,需要改正
2、将函数封装成模块

Code:
  1. import requests
  2. import bs4
  3. import re
  4. import numpy as ny
  5. import pandas as pd
  6. import matplotlib.pyplot as plt
  7. import matplotlib as mpl
  8. import os
  9. from pandas.core.frame import DataFrame
  10. %matplotlib inline
  11. #设置图形内嵌
  12. import matplotlib.style as stl
  13. stl.use('ggplot') #自带样式美化

  14. mpl.rcParams['font.sans-serif']=['SimHei']  # #指定默认字体 SimHei为黑体

  15. def opens(host):#获取地址
  16.    
  17.     headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.76'}
  18.     res = requests.get(host,headers = headers)
  19.    
  20.     return res

  21. def find_depth(res):#获取总共多少页
  22.     soup = bs4.BeautifulSoup(res.text,'html.parser')
  23.     depth = soup.find('span',class_='next').previous_sibling.previous_sibling.text
  24.     return int(depth)

  25. def find_movie(res):#获取表格信息
  26.     soup = bs4.BeautifulSoup(res.text,'html.parser')
  27.     title = [] # 电影名
  28.     takes = soup.find_all('div',class_='hd')
  29.     for i in takes:
  30.         title.append(i.a.span.text)
  31.         
  32.     ranks = [] #评分
  33.     takes = soup.find_all('span',class_='rating_num')
  34.     for i in takes:
  35.         ranks.append('%s'%i.text)
  36.       
  37.     tags = [] #标签
  38.     tags_d = []
  39.     takes = soup.find_all('div',class_='bd')
  40.     for i in takes:
  41.         try:
  42.             tags.append(i.p.text.split('\n')[1].strip() +
  43.                      i.p.text.split('\n')[2].strip())
  44.             #处理数据,获取年份
  45.             tags_str = ''.join(tags)
  46.             tags_str_d = tags_str.split('...')[1]
  47.             tags_d.append(tags_str_d[:4])
  48.         except:
  49.             continue
  50.    
  51.     result = []
  52.     lenght = len(title)
  53.     for i in range(lenght):
  54.         result.append([title[i],ranks[i],tags_d[i]])#生成二维数据,电影名,评分,年份

  55.     return result
  56.    
  57.     def fun4(df):
  58.         
  59.         pass
  60.    
  61. def main():
  62.     host = "https://movie.douban.com/top250"
  63.     res = opens(host)
  64.     depth = find_depth(res)
  65.    
  66.     result = []
  67.     for i in range(depth):
  68.         url = host + '/?start=' + str(25*i)
  69.         res = opens(url)
  70.         result.extend(find_movie(res))     
  71. #########################
  72.     with open("onex.txt", "w", encoding="utf-8") as f:
  73.     for each in result:
  74.         f.write(each)
  75. #######################      
  76.     result = []
  77.     fk = pd.read_table('onex.txt',header=None)#读取txt
  78.     for i in range(250):
  79.         result.append(str(fk.iloc[i,0]))
  80.     a = result.copy()
  81.     b = result.copy()
  82.     c = result.copy()
  83.     result_name = []
  84.     result_rank = []
  85.     result_year = []
  86.     for i in range(250):#存进列表
  87.         result_name.append(a[i].split(' ')[0])
  88.         result_rank.append(float(b[i].split('评分:')[1][:3]))
  89.         if ((c[i].split('/')[-3]).removesuffix('\xa0')[-4:]).isdigit() == True :#将无效值变为None
  90.             result_year.append(int((c[i].split('/')[-3]).removesuffix('\xa0')[-4:]))
  91.         else:
  92.             result_year.append(None)
  93.             
  94. #     pot = []
  95. #     for i in range(250):
  96. #         pot.append([result_name[i],result_rank[i],result_year[i]])

  97.     dic = {'name':result_name,'rank':result_rank,'year':result_year}#生成字典
  98.     pot = DataFrame(dic)#获得二维表格数据
  99.    
  100.     pot_r = pot.groupby('rank').count()#按评分分组
  101.     result_pot_r = pot_r.sort_values('rank',ascending=True)['name']
  102.    
  103.     fig= plt.figure(num = 1,figsize=(10,5))
  104.     x = ny.linspace(8.3,9.7,15)
  105.     plt.bar(range(len(result_pot_r)),result_pot_r,tick_label=x)#生成评分分布图表
  106.     plt.title('电影评分分布情况')
  107.     for i in range(len(result_pot_r)):
  108.         plt.text(i-0.1,result_pot_r.iloc[i],result_pot_r.iloc[i],fontsize=12,verticalalignment='center')#标签
  109.     plt.tight_layout()
  110.    
  111.     #按年份进行分组
  112.     bins = ny.arange(1910,2020,10)
  113.     labels = [str(bins[i]) + '-' + str(bins[i+1]) for i in range(0,len(bins)-1)]
  114.     pot_y1 = pd.cut(pot['year'],bins=bins,labels=labels)#划分区间
  115.     pot_y1_count = pd.value_counts(pot_y1)#统计数量   

  116.     fig= plt.figure(num = 2,figsize=(8,3))
  117.     plt.bar(labels,pot_y1_count)#生成年代分布图表
  118.     plt.title('电影年代分布情况')
  119.     for i in range(len(labels)):
  120.         plt.text(i-0.1,pot_y1_count[i],pot_y1_count[i],fontsize=12,verticalalignment='center')#标签
  121.     plt.tight_layout()

  122. if __name__ == '__main__':
  123.     main()
复制代码



附件如下:


1.jpg
2.jpg

item1.rar

39.3 KB, 下载次数: 3

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-3-2 21:07:40 | 显示全部楼层
此帖仅作者可见
小甲鱼最新课程 -> https://ilovefishc.com

使用道具 举报

发表于 2022-3-22 19:44:21 | 显示全部楼层
此帖仅作者可见
小甲鱼最新课程 -> https://ilovefishc.com

使用道具 举报

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

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-29 13:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表