0

I want to import all the contacts number from user's phone address book and store them in the database but since I want to do some processing on them later, all of the phone numbers should have a unify format.

I have done some research on the Internet and I find out that there are three major format for phone-numbers: (source: googlei18n/libphonenumber)

  • INTERNATIONAL
  • NATIONAL
  • E164

Then I export and extract my phone contact numbers but I understand that there are plenty of different format numbers from different countries and carriers.

Here's some example:

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

Based-on google's library, if you want to convert any phone number to a different format, I guess, you have to know which country they're belong to and in my case, every contact belongs to different country.

Now, my question is what are the steps to prepare and convert all of them to one specific format?

I need to know the whole concept of this operation but If you want to write code, any programming language is okay.

‌‌R‌‌‌.
  • 2,818
  • 26
  • 37

1 Answers1

2

These answers use the python version of libphonenumber, but AFAIK the rules are the same in other ports.

Converting an arbitrary international number to a unified format is really easy...

>>> 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'

And you don't need to know country for international format numbers (it has a '+' at the start).

>>> 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'

The only time you need to know a number's country is when the source number is not in valid international format...

>>> 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'

The country code you pass to parse only serves as a fallback in the case that the input number can't be parsed as international.

QuestionC
  • 10,006
  • 4
  • 26
  • 44