週五不困,無聊寫了一個 Python 腳本,功能很簡單:獲取新浪關於各個國家疫情數據,並寫入 md 文件並預覽,定時去獲取數據,有新數據則生成新的 markdown 內容拼接在文件最後。python
因爲功能和代碼都很簡單,直接上代碼shell
# -*-coding:utf8-*- import re,requests,json,pprint,time import os pattern=re.compile(r'^try{sinajp_15844213244528328543098388435\((.*?)\);}catch\(e\){};') lasttimes='00:00:00' while True: res=requests.get('https://gwpre.sina.cn/ncp/foreign?_=1584421324452&callback=sinajp_15844213244528328543098388435') match=pattern.search(res.text) if match: obj=json.loads(match.group(1)) resultObj=obj['result'] times=resultObj['times'] # 截止時間 timesMatch=re.search(r'截至(\d{2})月(\d{2})日(\d{2})時(\d{2})分',times) if timesMatch: times=timesMatch.group(1)+'月'+timesMatch.group(2)+'日 '+timesMatch.group(3)+':'+timesMatch.group(4) if times==lasttimes: continue else: lasttimes=times totalObj=resultObj['total'] certain=totalObj['certain'] # 累計確診 die=totalObj['die'] # 死亡 recure=totalObj['recure'] # 治癒 certain_inc=totalObj['certain_inc'] # 確診增長 die_inc=totalObj['die_inc'] # 死亡增長 recure_inc=totalObj['recure_inc'] # 治癒增長 # 各國數據列表 worldlistArr=resultObj['worldlist'] worldlistArr.sort(key=lambda x: int(x.get('conNum','0')),reverse=True) fo=open('./coronavirus.md','a') fo.writelines('\n# '+times+'\n') fo.writelines('感染國家總數:'+str(len(worldlistArr))+'\n') fo.writelines('```\n累計確診:'+certain.rjust(10,' ')+' 較昨日:'+certain_inc+'\n'+'累計死亡:'+die.rjust(10,' ')+' 較昨日:'+die_inc+'\n'+'累計治癒:'+recure.rjust(10,' ')+' 較昨日:'+recure_inc+'\n```\n') fo.writelines('|國家|新增確診|累計確診|新增死亡|累計死亡|累計治癒|'+'\n') fo.writelines('|:--:|---:|---:|---:|---:|---:|'+'\n') top15=worldlistArr[:15] pattient_countrys=['澳大利亞','加拿大','巴西','印度','丹麥','越南','新加坡','俄羅斯','塞爾維亞','巴基斯坦',] pattient=[c for c in worldlistArr if c['name'] in pattient_countrys] for countryObj in top15: name=countryObj['name'] # 國家 if name=='中國': continue conadd=countryObj['conadd'] # 新增確診 conNum=countryObj['conNum'] # 累計確診 deathadd=countryObj['deathadd'] # 新增死亡 deathNum=countryObj['deathNum'] # 累計死亡 cureNum=countryObj['cureNum'] # 累計治癒 fo.writelines('|'+name+'|'+conadd+'|'+conNum+'|'+deathadd+'|'+deathNum+'|'+cureNum+'|\n') fo.writelines('\n特別關心'+'\n') fo.writelines('|國家|新增確診|累計確診|新增死亡|累計死亡|累計治癒|'+'\n') fo.writelines('|:--:|---:|---:|---:|---:|---:|'+'\n') for countryObj in pattient: name=countryObj['name'] # 國家 conadd=countryObj['conadd'] # 新增確診 conNum=countryObj['conNum'] # 累計確診 deathadd=countryObj['deathadd'] # 新增死亡 deathNum=countryObj['deathNum'] # 累計死亡 cureNum=countryObj['cureNum'] # 累計治癒 fo.writelines('|'+name+'|'+conadd+'|'+conNum+'|'+deathadd+'|'+deathNum+'|'+cureNum+'|\n') fo.close() # 用 Markdown IDE 打開 .md 文件進行預覽 os.system('open -a "/Applications/Typora.app" ./coronavirus.md') for i in range(1,61): time.sleep(10) print(i*10)2
pip3 install requests
修改 Markdown 的打開方式。因爲我電腦安裝 Marodown 編輯器是 Typora
,因此腳本是 open -a "/Applications/Typora.app" ./coronavirus.md
。修改這裏的 ***.app
爲本身的 idejson
終端運行便可markdown
python3 coronavirus.py