首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用pycountry从名称获取国家/地区id

要使用 pycountry 库从国家/地区名称获取其对应的国家/地区代码(ID),你可以按照以下步骤进行:

  1. 安装 pycountry 库(如果尚未安装):

pip install pycountry

  1. 使用 pycountry 库查找国家/地区名称并获取其代码。以下是一个示例代码:

import pycountry def get_country_code(country_name): try: country = pycountry.countries.lookup(country_name) return country.alpha_2 # 或者使用 country.alpha_3 获取三字母代码 except LookupError: return None # 示例用法 country_name = "China" country_code = get_country_code(country_name) if country_code: print(f"The country code for {country_name} is {country_code}.") else: print(f"Country name '{country_name}' not found.")

在这个示例中,pycountry.countries.lookup 方法用于查找国家/地区名称,并返回一个包含国家/地区信息的对象。你可以从这个对象中获取 alpha_2(两字母代码)或 alpha_3(三字母代码)。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券