0

我想从用户的电话通讯录中导入所有联系人号码并将它们存储在数据库中,但是由于我想稍后对它们进行一些处理,所以所有电话号码都应该具有统一的格式。

我在网上做了一些研究,发现电话号码主要有三种格式:(来源:googlei18n/libphonenumber

  • 国际的
  • 国民
  • E164

然后我导出并提取我的电话联系号码,但我知道有很多来自不同国家和运营商的不同格式的号码。

这里有一些例子:

 0123456789
 0 12-345 6789
 +6012345678
 +27 60 123 4567‬
 09131234567
 +98 (310) 1234567
 00982101234567

基于谷歌的图书馆,如果你想将任何电话号码转换为不同的格式,我想你必须知道他们属于哪个国家,在我的情况下,每个联系人都属于不同的国家。

现在,我的问题是准备并将它们全部转换为一种特定格式的步骤是什么?

我需要知道这个操作的整个概念,但是如果你想写代码,任何编程语言都可以。

4

1 回答 1

2

这些答案使用python版本的libphonenumber,但AFAIK规则在其他端口中是相同的。

将任意国际号码转换为统一格式真的很容易......

>>> import phonenumbers
>>> x = phonenumbers.parse('+1-904-566-6820')
>>> phonenumbers.is_valid_number(x)
True
>>> phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
'+1 904-566-6820'

而且你不需要知道国际格式号码的国家(它的开头有一个'+')。

>>> phonenumbers.format_number(phonenumbers.parse('+1-904-566-6820'), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
'+1 904-566-6820'
>>> phonenumbers.format_number(phonenumbers.parse('+1 (904) 566-6820'), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
'+1 904-566-6820'
>>> phonenumbers.format_number(phonenumbers.parse('+33 6 10 45 04 89'), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
'+33 6 10 45 04 89'

您唯一需要知道号码所在国家/地区的情况是源号码不是有效的国际格式...

>>> phonenumbers.format_number(phonenumbers.parse('(904) 566-6820'), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home15/jgalloway12/code/wdPhone/phonenumbers/phonenumberutil.py", line 2450, in parse
    "Missing or invalid default region.")
phonenumbers.phonenumberutil.NumberParseException: (0) Missing or invalid default region.
>>> phonenumbers.format_number(phonenumbers.parse('(904) 566-6820', 'US'), phonenumbers.PhoneNumberFormat.INTERNATIONAL)
'+1 904-566-6820'

您传递到的国家/地区代码parse仅在输入数字无法解析为国际的情况下用作后备。

于 2015-12-15T15:09:55.430 回答