phonenumbers library in python
Wajiha Abid
Software Engineer | Nodejs | Typescript | GraphQL | Socket.io | Laravel | React/Vue | Freelancer
Get different requirements daily, so the recent requirement I got was to extract the carriers of phone numbers, validate them e.g: is it mobile number or not and get the location of the number without using any third party API. So after some R&D, I got to know about the library in python named "phonenumbers" and with this library I easily extract the certain informations about the mobile number.
Pre-requisites:
Installations:
Install library with the following command:
pip install phonenumbers
Imports:
Import the phonenumbers module and some of it features which we will explore below.
import phonenumber
from phonenumbers import carrier
from phonenumbers import geocoders
Usage:
1. Parse Country Code:
Pass the number and get the country code of the phone number. It returns the object of class phonenumbers. It has 2 keys:
Syntax:
//number is encrypted here you have to pass the original number
x = phonenumbers.parse("+9231*****147", None)
print(x)
Output:
2. Number Validation:
Pass the parsed object to check the is number valid. It returns boolean (True\False).
Syntax:
领英推荐
// x is the same above parsed object in section 1 of "usage"
isPossible = phonenumbers.is_valid_number(x)
print("isValid:",isPossible)
Output:
3. Parse Detail:
3.1. Location:
We can get the location of the number in the specified language. Pass the parsed object and the language string e.g: 'en' for english ,'fr' for french.
Syntax:
// x is the same above parsed object in section 1 of "usage" and "geocoder" is imported in "import" section.
location =geocoder.description_for_number(x, "en")
print("location:",location)
Output:
3.2. Carrier/Operator:
We can easily get the carrier/operator of the number too like either the number belongs to Ufone, Verizon, Jazz service etc. It takes similar arguments, we provided in the location block (Section 3.1).
Syntax:
// x is the same above parsed object in section 1 of "usage" and "carrier" is imported in "import" section.
carriers = carrier.name_for_number(x, "en")
print("Carrier:",carriers)
Output:
Conclusion:
These were some simple methods of phonenumbers library. To explore more about the phonenumbers library checkout its documentation here. The code for the scenario I shared in the introduction is uploaded on the github, checkout here.
Thank you for the read and do share your experience with this library!.
Senior Planner in Oil & Gas
10 个月perfect