【发布时间】:2019-04-01 14:08:45
【问题描述】:
我正在学习 python 速成课程并在 pygal 世界地图上绘制人口。有些国家代码必须专门检索,因为它们的国家名称不标准。我开始尝试使用玻利维亚和刚果获得这个非标准国家代码,但在 pygal 地图上两者仍然是空白的。附件是两个相关模块,任何帮助将不胜感激。
获取国家代码的代码:
from pygal.maps.world import COUNTRIES
def get_country_code(country_name):
"""return the pygal 2-digit country code for
given country"""
for code, name in COUNTRIES.items():
if name == country_name:
return code
if country_name == 'Bolivia, Plurinational State of':
return 'bo'
elif country_name == 'Congo, the Democratic Republic of the':
return 'cd'
#if the country wasnt found, return none
return None
然后是导出到 pygal 映射的程序
import json
from pygal.maps.world import World
from pygal.style import RotateStyle
from country_codes import get_country_code
#load the data into a list
filename = 'population_data.json'
with open(filename) as f:
pop_data = json.load(f)
#build a dictionary of population data
cc_population = {}
#print the 2010 population for each country
for pop_dict in pop_data:
if pop_dict['Year'] == '2010':
country_name = pop_dict['Country Name']
population = int(float(pop_dict['Value']))
code = get_country_code(country_name)
if code:
cc_population[code] = population
#Group the countries into 3 population levels
cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
for cc, pop in cc_population.items():
if pop < 10000000:
cc_pops_1[cc] = pop
elif pop < 1000000000:
cc_pops_2[cc] = pop
else:
cc_pops_3[cc] = pop
wm_style = RotateStyle('#994033')
wm = World(style=wm_style)
wm.title = 'World population in 2010, by country'
wm.add('0-10 mil', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)
wm.render_to_file('world_population.svg')
【问题讨论】: