十分钟用 Python 绘制了近十年编程语言趋势图
先來個視頻體驗一下效果,文末還有視頻教程
1. 分析
我們需要獲取數(shù)據(jù),所以第一步需要從tiobe抓取近幾年的top編程語言的占比情況,其次存入 csv,最后使用 Python 繪制成表格。
2. 安裝包
python3?-m?pip?install?plotly python3?-m?pip?install?pandas3. 網(wǎng)頁分析
我們進(jìn)入 https://www.tiobe.com/tiobe-index/ 網(wǎng)站發(fā)現(xiàn)他下面有一個趨勢圖果不其然,我們右鍵點擊查看源文件就能看到他的數(shù)據(jù)
那么我們就可以使用 request 盤他了,下面是抓取和解析的代碼,可以配合 https://regex101.com/ 工具調(diào)試正則表達(dá)式。
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'?+?jif?index?==?0:time?+=?jelse:time?+=?'-'?+?jtemp?=?{'Programming':?name,'Percent':?value,'Date':?time}writer.writerow(temp) f.close()運行完成以后你就會發(fā)現(xiàn)程序目錄多了一個文件 programming.csv這樣我們的數(shù)據(jù)就準(zhǔn)備好了
4. 繪圖
繪圖之前還是需要把文件讀取到 Python 程序,這里使用了 pandas 也是非常簡單,讀取 csv 成功以后,使用?plotly 的 bar 方法來繪圖,直接上代碼。
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=?"十年編程語言趨勢圖(微信訂閱號:小猿學(xué)Python)") fig.show()等待1分鐘左右,他會自己創(chuàng)建好圖自動打開瀏覽器進(jìn)入演示,所以你學(xué)會了嗎?
如果你想看這個教程的視頻版,歡迎點擊閱讀原文查看。
? ???精 彩 文 章?
整理一份程序員常用的各類工具、技術(shù)站點
如何設(shè)計 API 接口,實現(xiàn)統(tǒng)一格式返回?
推薦 5 款好用的開源 Docker 工具
總結(jié)
以上是生活随笔為你收集整理的十分钟用 Python 绘制了近十年编程语言趋势图的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 整理一份程序员常用的各类工具、技术站点
- 下一篇: 微软官方上线的Python教程,7个章节