【问题标题】:Get continent name from country using pycountry使用 pycountry 从国家/地区获取大陆名称
【发布时间】:2019-09-18 11:17:08
【问题描述】:

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

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

我想从中获取大陆名称。

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

【问题讨论】:

  • @VikasYadav 感谢您的建议!所以根据这个我应该国家名称到 ISO_2 并从那个到大陆名称?
  • for country in pycountry.countries: countries[country.name] = country.alpha_2 这会将国家转换为 alpha_2,有没有这样的方法可以将国家名称转换为大陆名称?

标签: python country country-codes


【解决方案1】:

查看文档,这样的方法可以解决问题吗?:

country_alpha2_to_continent_code()

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

如果您首先需要获取可以使用的国家/地区代码:

country_name_to_country_alpha2(cn_name, cn_name_format="default")

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

完整示例:

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)

【讨论】:

  • 正是我想要的!谢谢
  • 实际上在这个解决方案中你会得到大陆代码,不是名字,而是其他的。
  • 考虑到只有 7 大洲而不是 195 个国家,我相信他将能够编写翻译代码 ;)
  • @RomanAlexandrovich 看 IsraMata 的例子,pycountry_converter 已经有convert_continent_code_to_continent_name 方法,你不需要自己转换。
【解决方案2】:
from pycountry_convert import country_alpha2_to_continent_code, country_name_to_country_alpha2

continents = {
    'NA': 'North America',
    'SA': 'South America', 
    'AS': 'Asia',
    'OC': 'Australia',
    'AF': 'Africa',
    'EU': 'Europe'
}

countries = ['India', 'Australia']

[continents[country_alpha2_to_continent_code(country_name_to_country_alpha2(country))] for country in countries]

不知道南极怎么办¯_(ツ)_/¯

【讨论】:

  • 哈哈谢谢老兄!
  • 请注意这里忘记了欧盟 :)
  • 需要:'EU': 'Europe',最后!
  • @RomanAlexandrovich 这个映射已经存在:pycountry_converter 已经有convert_continent_code_to_continent_name 方法,你不需要自己转换。
【解决方案3】:

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

【讨论】:

  • 这应该是公认的答案,因为它不会像上面的答案那样硬编码大陆名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 2017-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 2019-06-24
相关资源
最近更新 更多