zoukankan      html  css  js  c++  java
  • Python JSON

    世界人口图

    从https://datahub.io/网站搜索population,下载世界人口json数据。

    from pygal.maps.world import COUNTRIES
    
    def get_country_code(country_name):
        """根据指定的国家,返回pygal使用的两个字母的国别码"""
        for code, name in COUNTRIES.items():
            if name == country_name:
                return code
        # 如果没有找到指定的国家,就返回None
        return None
    
    
    if __name__ == '__main__':
        print(get_country_code('Andorra'))
        print(get_country_code('United Arab Emirates'))
        print(get_country_code('Afghanistan'))
    # world_population.py
    
    import json
    from country_codes import get_country_code
    import pygal_maps_world.maps as maps
    from pygal.style import RotateStyle, LightColorizedStyle
    
    # 将数据加载到一个列表中
    filename = 'data/population_data.json'
    with open(filename) as f:
        pop_data = json.load(f)
    
    # 创建一个包含人口数量的字典
    cc_populations = {}
    
    # 打印每个国家2016年的人口数量
    for pop_dict in pop_data:
        for key in pop_dict:
            if key == 'Year_2016':
                country = pop_dict['Country']
                try:
                    population = int(pop_dict[key])
                except:
                    pass
                code = get_country_code(country)
                if code:
                    print(code + ': ' + str(population))
                    cc_populations[code] = population
                else:
                    print('ERROR - ' + country)
    
    # 根据人口数量将所有国家分成三组
    cc_pops_1, cc_pops_2, cc_pops_3 = {}, {}, {}
    for cc, pop in cc_populations.items():
        if pop < 10000000:
            cc_pops_1[cc] = pop
        elif pop < 1000000000:
            cc_pops_2[cc] = pop
        else:
            cc_pops_3[cc] = pop
    
    # 看看每组分别包含多少个国家
    print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))
    
    wm_style = RotateStyle('#336699', base_style=LightColorizedStyle)
    wm = maps.World(style=wm_style)
    wm.title = 'World Population in 2016, by Country'
    wm.add('0-10m', cc_pops_1)
    wm.add('10m-1bn', cc_pops_2)
    wm.add('>1bn', cc_pops_3)
    
    wm.render_to_file('world_population.svg')

    Resistance is Futile!
  • 相关阅读:
    安装future包,django-crispy-forms
    django学习笔记(七)-----视图
    django学习笔记(六)-----模型
    django学习笔记(五)------path
    django学习笔记(四)---基本流程三(视图,模板基本使用)
    django学习笔记(三)--基本流程二---admin站点管理
    django学习笔记(二)基本流程一
    C#时间
    可空类型的DateTime转换成字符串
    asp.net mvc Razor一点小注意点
  • 原文地址:https://www.cnblogs.com/noonjuan/p/10847008.html
Copyright © 2011-2022 走看看