我正在尝试进行Python速成课程16-7,我编写了此程序,在地图上绘制了不同的国家/地区,但费用数据仅是最后一个国家/地区的价值,我花了几天的时间进行尝试解决这个问题,但似乎没有效果。我做错了什么?请帮助,我非常感谢!非常感谢你!
expenses.py
import csv
from pygal.maps.world import World
from pygal.style import LightColorizedStyle as LCS, RotateStyle as RS
from country_codes import get_country_code
#load the data into a list.
filename = 'expense.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
header_row = next(reader)
header_row = next(reader)
header_row = next(reader)
header_row = next(reader)
cc_expenses = {}
country_names, expenses = [], []
for row in reader:
country_name = row[0]
expense = row[61]
country_names.append(country_name)
expenses.append(expense)
code = get_country_code(country_name)
if code:
cc_expenses[code]= expense
# Everything work up to this point.
# Group the countries into 3 population levels.
cc_es_1, cc_es_2, cc_es_3 = {}, {}, {}
for cc, e in cc_expenses.items():
e = int(float(expense))
if e < 20:
cc_es_1[cc] = e
elif e < 40:
cc_es_2[cc] = e
else:
cc_es_3[cc] = e
# See how many countries are in each level.
print(len(cc_es_1), len(cc_es_2), len(cc_es_3))
wm_style = RS('#336699', base_style=LCS)
wm = World(style=wm_style)
wm.title = 'World Expense(% of GDP) in 2017, by Country'
wm.add('0-20', cc_es_1)
wm.add('20-40', cc_es_2)
wm.add('>40', cc_es_3)
wm.render_to_file('world_expenses.svg')
**countries.py**
from pygal.maps.world import COUNTRIES
for country_code in sorted(COUNTRIES.keys()):
print(country_code, COUNTRIES[country_code])
**country_codes.py**
from pygal.maps.world import COUNTRIES
from pygal.maps.world import World
def get_country_code(country_name):
'''Return the Pygal 2-digit country code for the given country.'''
for code, name in COUNTRIES.items():
if name == country_name:
return code
# If the country wasn't found, return None.
return None
expense.csv https://data.worldbank.org/indicator/GC.XPN.TOTL.GD.ZS?view=chart
我按照书中的说明下载csv文件