从Python中的国家代码获取电话号码的国际前缀

7

是否可以使用python-phonenumbers或其他Python库从两个字母的国家代码(ISO 3166-1 alpha-2)获取国家呼叫代码?

phonenumbers库中的示例侧重于从号码中提取国家代码,但我想要做相反的事情,类似于:

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


你可以通过解析以下页面上的表格来创建一个字典,尽管你需要从国家字母代码列中切掉前两个字符 - https://countrycode.org/ - thefragileomen
如果您查看以下页面上的__示例用法__:链接,您可以看到一些使用解析和国家代码的示例,以获取电话号码。 - sshashank124
这并不是一个真正的编程问题,而是一个资源问题。您可以解析维基百科http://en.wikipedia.org/wiki/List_of_country_calling_codes http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 - tommy.carstensen
4个回答

8

我不知道是否有任何适用于此的Python库,但是这里提供了一个包含所有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
编辑: 上述链接无法访问,但我在Github上找到了一个包含这些数据(以及更多内容)的存储库

那个链接已经失效了,因为该域名无法再被解析。 - Anthon
@Anthon 感谢提醒,我已经添加了一个新来源的链接(但还没有更新代码)。 - L3viathan

8

使用该库。

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.

最终:
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)

以下函数将根据提供的ISO代码为您提供调用代码:
```javascript function getCallingCode(isoCode) { const callingCodes = { AD: "+376", AE: "+971", AF: "+93", // and so on... }; return callingCodes[isoCode]; } ```
请注意,此函数返回的是字符串形式的呼叫代码,例如“+376”。
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

6

phonenumbers 库实际上有一个 country_code_for_region() 函数(至少在版本8.10.5中):

>>> import phonenumbers
>>> phonenumbers.country_code_for_region("GB")
44

0

使用python-phonenumbers,您可以利用COUNTRY_CODE_TO_REGION_CODE映射,它是一个字典,将国际呼叫代码(int)作为键和国家代码(str)作为值。只需反转字典即可完成工作。
这里有一个示例(与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'] ) )

希望它能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接