从python中的国家/地区代码中获取国家/地区名称? [英] Get country name from Country code in python?

查看:1297
本文介绍了从python中的国家/地区代码中获取国家/地区名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了2个python库:电话号码

I have worked with 2 python libraries: phonenumbers, pycountry. I actually could not find a way to give just country code and get its corresponding country name.

phonenumbers中,您需要为parse提供完整的数字.在pycountry中,仅获取国家/地区ISO.

In phonenumbers you need to provide full numbers to parse. In pycountry it just get country ISO.

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

Is there a solution or a method in any way to give the library country code and get country name?

推荐答案

phonenumbers库的文档不足.相反,他们建议您查看原始的Google项目以进行单元测试,以了解功能.

The phonenumbers library is rather under-documented; instead they advice you to look at the original Google project for unittests to learn about functionality.

PhoneNumberUtilTest单元测试似乎涵盖了您的特定用例;使用

The PhoneNumberUtilTest unittests seems to cover your specific use-case; mapping the country portion of a phone number to a given region, using the getRegionCodeForCountryCode() function. There is also a getRegionCodeForNumber() function that appears to extract the country code attribute of a parsed number first.

确实,确实有相应的 phonenumbers.phonenumberutil.region_code_for_country_code() > c8> 函数在Python中执行相同的操作:

And indeed, there are corresponding phonenumbers.phonenumberutil.region_code_for_country_code() and phonenumbers.phonenumberutil.region_code_for_number() functions to do the same in 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中使用该代码:

The resulting region code is a 2-letter ISO code, so you can use that directly in 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()而不使用电话号码,只需输入国家/地区代码:

Note that the .country_code attribute is just an integer, so you can use phonenumbers.phonenumberutil.region_code_for_country_code() without a phone number, just a country code:

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

这篇关于从python中的国家/地区代码中获取国家/地区名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆