如何使用python将国家/地区名称转换为ISO 3166-1 alpha-2值 [英] How to convert country names to ISO 3166-1 alpha-2 values, using python

查看:1026
本文介绍了如何使用python将国家/地区名称转换为ISO 3166-1 alpha-2值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的国家/地区列表:

I have a list of countries like:

countries=['American Samoa', 'Canada', 'France'...]

我想像这样转换它们:

countries=['AS', 'CA', 'FR'...]

是否有任何模块或任何方法可以转换它们?

Is there any module or any way to convert them?

推荐答案

有一个名为pycountry .

There is a module called pycountry.

这是示例代码:

import pycountry

input_countries = ['American Samoa', 'Canada', 'France']

countries = {}
for country in pycountry.countries:
    countries[country.name] = country.alpha_2

codes = [countries.get(country, 'Unknown code') for country in input_countries]

print(codes)  # prints ['AS', 'CA', 'FR']

这篇关于如何使用python将国家/地区名称转换为ISO 3166-1 alpha-2值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆