从python的国际电话号码中获取一个国际号码

2024-06-03 02:41:50 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用python-phonenumbers或其他python库从两个字母的国家代码(ISO 3166-1 alpha-2)中获取国家/地区调用代码?在

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

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


Tags: 代码alpha示例cl字母iso数字国家
3条回答

使用lib。在

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.

最终:

^{pr2}$

以下函数将从提供的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

这给了你:

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

使用python-phonenumbers您可以利用国家/地区代码到地区代码映射,它是一个以国际呼叫代码(int)为键,以国家代码(str)为值的dict。你只要把口述反过来,工作就完成了。
这里有一个例子(与toast38cozacgte的答案非常相似):

REGION_CODE_TO_COUNTRY_CODE = {}
for k, vs in phonenumbers.COUNTRY_CODE_TO_REGION_CODE.items(): # prefix -> country code: 39 -> 'IT'
    for v in vs:   #because a prefix could belong to more countries
       REGION_CODE_TO_COUNTRY_CODE[v] = k # country code-> prefix : 'IT' -> 39# now you have your reversed map

print( 'Italy country prefix: +'+ str( REGION_CODE_TO_COUNTRY_CODE['IT'] ) )

希望能有所帮助

我不知道有什么python库支持这个,但是here是一个csv,包含所有ISO 3166-1α-2代码及其数字前缀,从那里查找应该很简单:

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

编辑:上面的链接已经断开了,但是我在Github上找到了一个repository with that data (and more)。在

相关问题 更多 >