先来个视频体验一下效果,文末还有视频教程
1. 分析
我们需要获取数据,所以第一步需要从tiobe抓取近几年的top编程语言的占比情况,其次存入 csv,最后使用 Python 绘制成表格。
2. 安装包
1 2 | python3 -m pip install plotly python3 -m pip install pandas |
3. 网页分析
我们进入 https://www.tiobe.com/tiobe-index/ 网站发现他下面有一个趋势图果不其然,我们右键点击查看源文件就能看到他的数据
那么我们就可以使用 request 盘他了,下面是抓取和解析的代码,可以配合 https://regex101.com/ 工具调试正则表达式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import requests import re import os import csv url = 'https://www.tiobe.com/tiobe-index/' headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36' } f = open('programming.csv', 'w', newline='') writer = csv.DictWriter(f, ['Programming','Percent','Date']) writer.writeheader() response = requests.get(url, headers=headers) html = response.text result = ''.join(re.findall(r'series: (.*?)\}\);', html, re.DOTALL)) result = re.findall(r'({.*?})', result, re.DOTALL) for item in result: name = ''.join(re.findall(r"{name : '(.*?)'", item, re.DOTALL)) data = re.findall(r"\[Date.UTC(.*?)\]", item, re.DOTALL) for i in data: i = i.replace(' ', '') i = re.sub(r'[()]', '', i) value = i.split(',')[-1] time_list = i.split(',')[:3] time = "" for index, j in enumerate(time_list): if index !=0: if len(j) == 1: j = '0' + j if index == 0: time += j else: time += '-' + j temp = { 'Programming': name, 'Percent': value, 'Date': time } writer.writerow(temp) f.close() |
运行完成以后你就会发现程序目录多了一个文件 这样我们的数据就准备好了
4. 绘图
绘图之前还是需要把文件读取到 Python 程序,这里使用了 pandas 也是非常简单,读取 csv 成功以后,使用 plotly 的 bar 方法来绘图,直接上代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import plotly.express as px import pandas as pd df = pd.read_csv('programming.csv') fig = px.bar(df, y="Programming", x="Percent", animation_frame="Date", range_x=[0, df.Percent.max()], orientation='h', text='Percent', color="Programming") fig.update_layout(width=500, height=400, xaxis_showgrid=False, yaxis_showgrid=False, showlegend=False) fig.update_xaxes(title_text= "十年编程语言趋势图(微信订阅号:小猿学Python)") fig.show() |
等待1分钟左右,他会自己创建好图自动打开浏览器进入演示,所以你学会了吗?
如果你想看这个教程的视频版,欢迎点击阅读原文查看。
精 彩 文 章
-
整理一份程序员常用的各类工具、技术站点
-
如何设计 API 接口,实现统一格式返回?
-
推荐 5 款好用的开源 Docker 工具
1 2 3 4 5 6 7 8 | END 来和小伙伴们一起向上生长呀~~~ 扫描下方二维码,添加小詹微信,可领取千元大礼包并申请加入 Python学习交流群,群内仅供学术交流,日常互动,如果是想发推文、广告、砍价小程序的敬请绕道!一定记得备注「交流学习」,我会尽快通过好友申请哦! (添加人数较多,请耐心等待) (扫码回复 1024 即可领取IT资料包) |