I am having Mobile numbers in below format with no "+" sign in front of mobile numbers. How to get country from these format of numbers. I checked documentation,"+" sign is required. Any way to add '+' sign manually before it check for number to avoid parsing exception.
Mobile_Number: 9687655xxxx
Mobile_Number: 6142499xxxx
Mobile_Number: 20109811xxxx
py script-
import phonenumbers
from phonenumbers import geocoder
query = phonenumbers.parse("96650072xxxx", None)
print (geocoder.description_for_number(query, "en"))
print(query.country_code)
Error-
<>@ubuntu:~/elk$ python3 a.py
Traceback (most recent call last):
File "a.py", line 4, in <module>
query = phonenumbers.parse("96650072xxxx", None)
File "/home/<>/.local/lib/python3.6/site-packages/phonenumbers/phonenumberutil.py", line 2855, in parse
"Missing or invalid default region.")
phonenumbers.phonenumberutil.NumberParseException: (0) Missing or invalid default region.
Output after adding '+' sign
<>@ubuntu:~/<..>$ python3 a.py
Saudi Arabia
966
Ref link- https://pypi.org/project/phonenumbers/
If your source dataset is just missing the leading +
you can just add it in the parse call.
original_phonenumber = "96650072xxxx"
query = phonenumbers.parse(f"+{original_phonenumber}")
If you have a mixed dataset, you need to check first if your phonenumber actually starts with +
original_phonenumber = "96650072xxxx"
if not original_phonenumber.startswith("+"):
original_phonenumber = f"+{original_phonenumber}"
query = phonenumbers.parse(original_phonenumber)
But that's bad practice, so I would instead advise you to fix your source dataset. Are you sure that only the leading +
is missing and not the entire country code?