要使用 pycountry
库从国家/地区名称获取其对应的国家/地区代码(ID),你可以按照以下步骤进行:
pycountry
库(如果尚未安装):pip install pycountry
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
(三字母代码)。
领取专属 10元无门槛券
手把手带您无忧上云