从python中的国家/地区代码获取电话号码的国际前缀

Mat*_*att 4 python internationalization phone-number

是否可以使用python-phonenumbers或其他python lib来获取一个国家/地区代码来自两个字母的国家代码(ISO 3166-1 alpha-2)?

phonenumberslib中的示例着重于从数字中提取国家/地区代码,但我想做相反的事情,例如:

"US" -> "1" "GB" -> "44" "CL" -> "56"

小智 6

使用库。

In [1]: from phonenumbers import COUNTRY_CODE_TO_REGION_CODE

In [2]: COUNTRY_CODE_TO_REGION_CODE
Out[2]: 
{1: ('US',
     'AG',
     'AI',

....
 7: ('RU', 'KZ'),
 20: ('EG',),
 27: ('ZA',),
 30: ('GR',),
 31: ('NL',),
 32: ('BE',),
 33: ('FR',),
 34: ('ES',),
 36: ('HU',),
 39: ('IT', 'VA'),
 40: ('RO',),
 ... snip.
Run Code Online (Sandbox Code Playgroud)

最终 :

from phonenumbers import COUNTRY_CODE_TO_REGION_CODE, REGION_CODE_FOR_NON_GEO_ENTITY
REGION_CODE_TO_COUNTRY_CODE = {}

for country_code, region_codes in COUNTRY_CODE_TO_REGION_CODE.items():
    for region_code in region_codes:
        if region_code == REGION_CODE_FOR_NON_GEO_ENTITY:
            continue
        if region_code in REGION_CODE_TO_COUNTRY_CODE:
            raise ValueError("%r is already in the country code list" % region_code)
        REGION_CODE_TO_COUNTRY_CODE[region_code] = str(country_code)
Run Code Online (Sandbox Code Playgroud)

以下函数将为您提供来自提供的 iso 代码的调用代码:

def get_calling_code(iso):
  for code, isos in COUNTRY_CODE_TO_REGION_CODE.items():
    if iso.upper() in isos:
        return code
  return None
Run Code Online (Sandbox Code Playgroud)

这给了你:

get_calling_code('US')
>> 1
get_calling_code('GB')
>> 44
Run Code Online (Sandbox Code Playgroud)


Ski*_*rou 6

phonenumbers库实际上有(至少从版本 8.10.5 开始)一个country_code_for_region()函数\xe2\x80\xaf:

\n
>>> import phonenumbers\n>>> phonenumbers.country_code_for_region("GB")\n44\n
Run Code Online (Sandbox Code Playgroud)\n


L3v*_*han 5

我不知道有任何python lib,但是这里有一个带有所有ISO 3166-1 alpha-2代码及其编号前缀的csv,从那里查找它应该是微不足道的:

import csv

country_to_prefix = {}

with open("countrylist.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        country_to_prefix[row["ISO 3166-1 2 Letter Code"]] = row["ITU-T Telephone Code"]

print country_to_prefix["US"] # +1
print country_to_prefix["GB"] # +44
print country_to_prefix["CL"] # +56
Run Code Online (Sandbox Code Playgroud)

编辑:上面的链接已经关闭,但我在Github上找到了一个包含该数据存储库(以及更多).