从python中的国家代码获取国家名称?

新手上路,请多包涵

我使用过 2 个 python 库: phonenumberspycountry 。我实际上找不到一种方法来只给出国家代码并获得其相应的国家名称。

phonenumbers 中,您需要向 parse 提供完整的数字。在 pycountry 它只是获得国家 ISO。

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

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

阅读 1.6k
2 个回答

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

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

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

 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'

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

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

 from phonenumbers.phonenumberutil import country_code_for_region

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

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

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