使用pycountry从国家获取大陆名称

新手上路,请多包涵

如何使用 pycountry 从国家名称转换大洲名称。我有一个这样的国家列表

country = ['India', 'Australia', ....]

我想从中获取大陆名称。

continent = ['Asia', 'Australia', ....]

原文由 VIBHU BAROT 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

查看文档,这样的事情会成功吗?:

country_alpha2_to_continent_code()

它将国家代码(例如:NO、SE、ES)转换为大陆名称。

如果您首先需要获取国家代码,您可以使用:

country_name_to_country_alpha2(cn_name, cn_name_format=“默认”)

从国家名称中获取国家代码。

完整示例:

 import pycountry_convert as pc

country_code = pc.country_name_to_country_alpha2("China", cn_name_format="default")
print(country_code)
continent_name = pc.country_alpha2_to_continent_code(country_code)
print(continent_name)

原文由 Oliver H. D. 发布,翻译遵循 CC BY-SA 4.0 许可协议

pycountry-convert 中提供了您需要的所有工具。

下面是一个示例,说明如何使用 pycountry 的工具创建自己的函数以将国家/地区名称直接转换为大陆名称:

 import pycountry_convert as pc

def country_to_continent(country_name):
    country_alpha2 = pc.country_name_to_country_alpha2(country_name)
    country_continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
    country_continent_name = pc.convert_continent_code_to_continent_name(country_continent_code)
    return country_continent_name

# Example
country_name = 'Germany'
print(country_to_continent(country_name))

Out[1]: Europe

希望能帮助到你!

请记住,您可以使用 ‘??函数名’

 ?? pc.country_name_to_country_alpha2

原文由 Isra Mata 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题