【问题标题】:Can't get last few countries to show their population on pygal world map无法让最后几个国家在 pygal 世界地图上显示其人口
【发布时间】: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')

【问题讨论】:

    标签: python pygal


    【解决方案1】:

    看起来您正在检查 Pygal 世界地图模块中定义的国家/地区名称,但应该检查 json 数据文件中使用的名称。

    例如,假设 json 文件使用名称“玻利维亚”,您需要将该特定比较更改为

    if country_name == 'Bolivia':
        return 'bo'
    

    您可以通过在函数的最后一个return 之前添加print 语句来识别需要以这种方式处理的任何其他国家/地区。当您运行该程序时,控制台上将列出所有缺失的国家/地区以及您需要检查的特定文本。

    #if the country wasnt found, return none
    print(country_name)
    return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2011-02-12
      • 2017-09-13
      • 1970-01-01
      相关资源
      最近更新 更多