我曾与2个python库:phonenumbers,pycountry。实际上我找不到一个只给出国家代码并获得相应国家名称的方法。从国家代码在python中获取国家名称?
在phonenumbers
您需要提供完整的数字parse
。在pycountry
它只是得到国家的ISO。
是否有任何解决方案或方法来给图书馆国家代码和国名?
我曾与2个python库:phonenumbers,pycountry。实际上我找不到一个只给出国家代码并获得相应国家名称的方法。从国家代码在python中获取国家名称?
在phonenumbers
您需要提供完整的数字parse
。在pycountry
它只是得到国家的ISO。
是否有任何解决方案或方法来给图书馆国家代码和国名?
phonenumbers
库文档相当不足;相反,他们建议您查看Google单元测试的原始项目,以了解功能。
PhoneNumberUtilTest
unittests似乎涵盖您的具体使用情况;使用getRegionCodeForCountryCode()
function将电话号码的国家部分映射到给定区域。还有一个getRegionCodeForNumber()
function似乎首先提取解析号码的国家/地区代码属性。
确实,有相应的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
所得区域码是一个双字母ISO代码,所以你可以直接使用pycountry
:
>>> import pycountry
>>> country = pycountry.countries.get(alpha2=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'
感谢您的时间和答案。正如我在问题中所说的,我只是把国家代码和国家代码的数字不同。所以例如我有+1不是完整的数字。我知道如何使用解析函数,但问题是我只有国家代码。 – ALH
@AlirezaHos:但是'PhoneNumber.country_code'只是一个整数*,这就是'region_code_for_country_code()'所需要的。更新了答案以突出显示。 –
想必当你说国家代码,你的意思是国际长途代码。这是真的,还是你的意思是ISO 3166-1 alpha-2? – erip
请提供一个[最小,完整和可验证的示例](http://stackoverflow.com/help/mcve) –
看看'phonenumberutils.region_codes_for_country_code' –