【问题标题】:Get country name from Country code in python?从python中的国家代码获取国家名称?
【发布时间】:2016-11-27 20:43:14
【问题描述】:

我使用过 2 个 Python 库:phonenumberspycountry。我实际上找不到只提供国家代码并获得相应国家名称的方法。

phonenumbers 中,您需要向parse 提供完整号码。在pycountry 中,它只是获取国家/地区 ISO。

是否有任何解决方案或方法可以提供图书馆国家代码并获取国家名称?

【问题讨论】:

  • 大概当您说国家代码时,您的意思是国际电话代码。这是真的吗,还是您的意思是 ISO 3166-1 alpha-2?
  • 看看phonenumberutils.region_codes_for_country_code

标签: python phone-number


【解决方案1】:

phonenumbers 库的文档很少;相反,他们建议您查看原始的 Google 单元测试项目以了解功能。

PhoneNumberUtilTest unittests 似乎涵盖了您的特定用例;使用getRegionCodeForCountryCode() function 将电话号码的国家/地区部分映射到给定区域。还有一个getRegionCodeForNumber() function似乎是先提取一个解析号码的国家代码属性。

确实,在 Python 中有相应的 phonenumbers.phonenumberutil.region_code_for_country_code()phonenumbers.phonenumberutil.region_code_for_number() 函数可以做同样的事情:

import phonenumbers
from phonenumbers.phonenumberutil import (
    region_code_for_country_code,
    region_code_for_number,
)

pn = phonenumbers.parse('+442083661177')
print(region_code_for_country_code(pn.country_code))

演示:

>>> import phonenumbers
>>> from phonenumbers.phonenumberutil import region_code_for_country_code
>>> from phonenumbers.phonenumberutil import region_code_for_number
>>> pn = phonenumbers.parse('+442083661177')
>>> print(region_code_for_country_code(pn.country_code))
GB
>>> print(region_code_for_number(pn))
GB

生成的区域代码是 2 个字母的 ISO 代码,因此您可以直接在 pycountry 中使用它:

>>> import pycountry
>>> country = pycountry.countries.get(alpha_2=region_code_for_number(pn))
>>> print(country.name)
United Kingdom

注意.country_code 属性只是一个整数,所以你可以使用phonenumbers.phonenumberutil.region_code_for_country_code() 而不需要电话号码,只需要国家代码:

>>> region_code_for_country_code(1)
'US'
>>> region_code_for_country_code(44)
'GB'

【讨论】:

  • 请注意,这将无法区分加拿大或美国的号码,因为它们具有相同的国家代码。
  • 为此有:phonenumbers.geocoder.country_name_for_number(n, "en") == "Canada"
【解决方案2】:

小添加 - 您还可以通过字符串代码获取国家/地区前缀。例如:

from phonenumbers.phonenumberutil import country_code_for_region

print(country_code_for_region('RU'))
print(country_code_for_region('DE'))

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多