0

为这个程序导入正确的模块,然后转换'gdp.json'成 python 可以使用的对象json.load(f)

import json
import pygal
from pygal.style import LightColorizedStyle as LCS,RotateStyle as RC
from pygal.maps.world import World
from country_codes import get_country_code
#load data into a list
filename = 'gdp.json'
with open(filename) as f:
    gdp_data = json.load(f)

建立一个字典gdp_data

cc_gdps = {}
for gdp_dict  in gdp_data:
    if gdp_dict['Year'] == 2014:
        country_name = gdp_data["Country Name"]
        gdp = int(float(gdp_data['Value']))
        code = get_country_code(country_name)
    if code:
        cc_gdps[code] = gdp
#Group the countries into 3 gdp level
cc_gdps_1,cc_gdps_2,cc_gdps_3 = {},{},{}
for cc,gdp in cc_gdps.items():
    if gdp < 5000000000:
        cc_gdps_1[cc]=round(gdp/1000000000)
    elif gdp < 5000000000:
        cc_gdps_2[cc] = round(gdp/1000000000)
    else:
        cc_gdps_3[cc] = round(gdp/1000000000)
#see how many countries are in each level
print(len(cc_gdps_1),len(cc_gdps_2),len(cc_gdps_3))
wm_style = RC('#336699',base_style=LCS)
wm = World(style = wm_style)
wm.title = 'Global GDP in 2014, by country.'
wm.add('0-5bln',cc_gdps_1)
wm.add('5bln-50bln',cc_gdps_2)
wm.add('>50bln', cc_gdps_3)
wm.render_to_file('global_gdp.svg')

这是get_country_code(country_name)方法:

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 the country wasnt found,return none.
    return None

不知道会是什么……</p>

4

2 回答 2

0

这导致了问题:

country_name = gdp_data["Country Name"]
#                            ^^^

gdp_datalist类型,因此它只接受整数或切片,作为索引的字符串对列表没有意义。

于 2020-02-21T21:13:41.807 回答
0

我认为您的 get_country_code 函数存在问题。改成这样。

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
        else:
            #if the country wasnt found,return none.
            return None
于 2020-02-21T20:34:33.353 回答