Python制作疫情地圖
詳細講解視頻地址——詳細視頻講解
第三彈 繪制地圖
以下是 map_draw.py 文件源碼
from pyecharts import options as opts
from pyecharts.charts import Map
import os
class Draw_map():
# relativeTime為發(fā)布的時間,傳入時間戳字符串
# def get_time(self):
# relativeTime = int(relativeTime)
# return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(relativeTime))
def __init__(self):
if not os.path.exists('./map/china'):
os.makedirs('./map/china')
def get_colour(self,a,b,c):
result = '#' + ''.join(map((lambda x: "%02x" % x), (a,b,c)))
return result.upper()
'''
參數(shù)說明——area:地級市 variate:對應(yīng)的疫情數(shù)據(jù) province:省份(不含省字)
'''
def to_map_city(self,area, variate,province,update_time):
pieces = [
{"max": 99999999, "min": 10000, "label": "≥10000", "color": self.get_colour(102, 2, 8)},
{"max": 9999, "min": 1000, "label": "1000-9999", "color": self.get_colour(140, 13, 13)},
{"max": 999, "min": 500, "label": "500-999", "color": self.get_colour(204, 41, 41)},
{"max": 499, "min": 100, "label": "100-499", "color": self.get_colour(255, 123, 105)},
{"max": 99, "min": 50, "label": "50-99", "color": self.get_colour(255, 170, 133)},
{"max": 49, "min": 10, "label": "10-49", "color": self.get_colour(255,202,179)},
{"max": 9, "min": 1, "label": "1-9", "color": self.get_colour(255,228,217)},
{"max": 0, "min": 0, "label": "0", "color": self.get_colour(255,255,255)},
]
c = (
# 設(shè)置地圖大小
Map(init_opts=opts.InitOpts(width = '1000px', height='880px'))
.add("累計確診人數(shù)", [list(z) for z in zip(area, variate)], province, is_map_symbol_show=False)
# 設(shè)置全局變量 is_piecewise設(shè)置數(shù)據(jù)是否連續(xù),split_number設(shè)置為分段數(shù),pices可自定義數(shù)據(jù)分段
# is_show設(shè)置是否顯示圖例
.set_global_opts(
title_opts=opts.TitleOpts(title="%s地區(qū)疫情地圖分布"%(province), subtitle = '截止%s %s省疫情分布情況'%(update_time,province), pos_left = "center", pos_top = "10px"),
legend_opts=opts.LegendOpts(is_show = False),
visualmap_opts=opts.VisualMapOpts(max_=200,is_piecewise=True,
pieces=pieces,
),
)
.render("./map/china/{}疫情地圖.html".format(province))
)
def to_map_china(self,area, variate,update_time):
pieces = [{"max": 999999, "min": 1001, "label": ">10000", "color": "#8A0808"},
{"max": 9999, "min": 1000, "label": "1000-9999", "color": "#B40404"},
{"max": 999, "min": 100, "label": "100-999", "color": "#DF0101"},
{"max": 99, "min": 10, "label": "10-99", "color": "#F78181"},
{"max": 9, "min": 1, "label": "1-9", "color": "#F5A9A9"},
{"max": 0, "min": 0, "label": "0", "color": "#FFFFFF"},
]
c = (
# 設(shè)置地圖大小
Map(init_opts=opts.InitOpts(width='1000px', height='880px'))
.add("累計確診人數(shù)", [list(z) for z in zip(area, variate)], "china", is_map_symbol_show=False)
.set_global_opts(
title_opts=opts.TitleOpts(title="中國疫情地圖分布", subtitle='截止%s 中國疫情分布情況'%(update_time), pos_left="center", pos_top="10px"),
legend_opts=opts.LegendOpts(is_show=False),
visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True,
pieces=pieces,
),
)
.render("./map/中國疫情地圖.html")
)
以下是get_data.py 文件源碼
import requests
from lxml import etree
import json
import re
import openpyxl
class Get_data():
def get_data(self):
# 目標url
url = "https://voice.baidu.com/act/newpneumonia/newpneumonia/"
# 偽裝請求頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/80.0.3987.149 Safari/537.36 '
}
# 發(fā)出get請求
response = requests.get(url,headers=headers)
# 將請求的結(jié)果寫入文件,便于分析
with open('html.txt', 'w') as file:
file.write(response.text)
def get_time(self):
with open('html.txt','r') as file:
text = file.read()
# 獲取更新時間
time_in = re.findall('"mapLastUpdatedTime":"(.*?)"',text)[0]
time_out = re.findall('"foreignLastUpdatedTime":"(.*?)"',text)[0]
print('國內(nèi)疫情更新時間為 '+time_in)
print('國外疫情更新時間為 '+time_out)
return time_in,time_out
def parse_data(self):
with open('html.txt','r') as file:
text = file.read()
# 生成HTML對象
html = etree.HTML(text)
# 解析數(shù)據(jù)
result = html.xpath('//script[@type="application/json"]/text()')
# print(type(result))
result = result[0]
# print(type(result))
result = json.loads(result)
# print(type(result))
result = json.dumps(result['component'][0]['caseList'])
# print(result)
# print(type(result))
with open('data.json','w') as file:
file.write(result)
print('數(shù)據(jù)已寫入json文件...')
response = requests.get("https://voice.baidu.com/act/newpneumonia/newpneumonia/")
# 將請求的結(jié)果寫入文件,便于分析
with open('html.txt', 'w') as file:
file.write(response.text)
# 獲取時間
time_in = re.findall('"mapLastUpdatedTime":"(.*?)"', response.text)[0]
time_out = re.findall('"foreignLastUpdatedTime":"(.*?)"', response.text)[0]
print(time_in)
print(time_out)
# 生成HTML對象
html = etree.HTML(response.text)
# 解析數(shù)據(jù)
result = html.xpath('//script[@type="application/json"]/text()')
print(type(result))
result = result[0]
print(type(result))
result = json.loads(result)
print(type(result))
# 以每個省的數(shù)據(jù)為一個字典
data_in = result['component'][0]['caseList']
for each in data_in:
print(each)
print("\n" + '*' * 20)
data_out = result['component'][0]['globalList']
for each in data_out:
print(each)
print("\n" + '*' * 20)
'''
area --> 大多為省份
city --> 城市
confirmed --> 累計
died --> 死亡
crued --> 治愈
relativeTime -->
confirmedRelative --> 累計的增量
curedRelative --> 治愈的增量
curConfirm --> 現(xiàn)有確診
curConfirmRelative --> 現(xiàn)有確診的增量
diedRelative --> 死亡的增量
'''
# 規(guī)律----遍歷列表的每一項,可以發(fā)現(xiàn),每一項(type:字典)均代表一個省份等區(qū)域,這個字典的前11項是該省份的疫情數(shù)據(jù),
# 當key = 'subList'時,其結(jié)果為只有一項的列表,提取出列表的第一項,得到一系列的字典,字典中包含該城市的疫情數(shù)據(jù).
# 將得到的數(shù)據(jù)寫入excel文件
# 創(chuàng)建一個工作簿
wb = openpyxl.Workbook()
# 創(chuàng)建工作表,每一個工作表代表一個area
ws_in = wb.active
ws_in.title = "國內(nèi)疫情"
ws_in.append(['省份', '累計確診', '死亡', '治愈', '現(xiàn)有確診', '累計確診增量', '死亡增量', '治愈增量', '現(xiàn)有確診增量'])
for each in data_in:
temp_list = [each['area'], each['confirmed'], each['died'], each['crued'], each['curConfirm'],
each['confirmedRelative'], each['diedRelative'], each['curedRelative'],
each['curConfirmRelative']]
for i in range(len(temp_list)):
if temp_list[i] == '':
temp_list[i] = '0'
ws_in.append(temp_list)
# 獲取國外疫情數(shù)據(jù)
for each in data_out:
print(each)
print("\n" + '*' * 20)
sheet_title = each['area']
# 創(chuàng)建一個新的工作表
ws_out = wb.create_sheet(sheet_title)
ws_out.append(['國家', '累計確診', '死亡', '治愈', '現(xiàn)有確診', '累計確診增量'])
for country in each['subList']:
list_temp = [country['country'], country['confirmed'], country['died'], country['crued'],
country['curConfirm'], country['confirmedRelative']]
for i in range(len(list_temp)):
if list_temp[i] == '':
list_temp[i] = '0'
ws_out.append(list_temp)
# 保存excel文件
wb.save('./data.xlsx')
以下是 execution.py 文件 源碼
import map_draw
import json
map = map_draw.Draw_map()
# 格式
# map.to_map_china(['湖北'],['99999'],'1584201600')
# map.to_map_city(['荊門市'],['99999'],'湖北','1584201600')
# 獲取數(shù)據(jù)
with open('data.json', 'r') as file:
data = file.read()
data = json.loads(data)
# 中國疫情地圖
def china_map(update_time):
area = []
confirmed = []
for each in data:
print(each)
area.append(each['area'])
confirmed.append(each['confirmed'])
map.to_map_china(area,confirmed,update_time)
# 23個省、5個自治區(qū)、4個直轄市、2個特別行政區(qū) 香港、澳門和臺灣的subList為空列表,未有詳情數(shù)據(jù)
# 省、直轄市疫情地圖
def province_map(update_time):
for each in data:
city = []
confirmeds = []
province = each['area']
for each_city in each['subList']:
city.append(each_city['city']+"市")
confirmeds.append(each_city['confirmed'])
map.to_map_city(city,confirmeds,province,update_time)
if province == '上海' or '北京' or '天津' or '重慶':
for each_city in each['subList']:
city.append(each_city['city'])
confirmeds.append(each_city['confirmed'])
map.to_map_city(city,confirmeds,province,update_time)
以下是 main.py 文件 源碼
from get_data import Get_data
data = Get_data()
data.get_data()
time_in,time_out = data.get_time()
data.parse_data()
import execution
execution.china_map(time_in)
execution.province_map(time_in)
說明——
將以上四個文件保存,放在同一目錄下,直接執(zhí)行main.py,即可成功運行。
求點贊求關(guān)注(?ω?)qwqqqqq
詳細講解視頻地址——詳細視頻講解