Skip to content

Instantly share code, notes, and snippets.

@rho333
Last active September 1, 2016 04:42
Show Gist options
  • Save rho333/c8633577aa9c8a406282c39dc0ce5b68 to your computer and use it in GitHub Desktop.
Save rho333/c8633577aa9c8a406282c39dc0ce5b68 to your computer and use it in GitHub Desktop.
Internationalises valid phone numbers given for a particular country, to E.164
import re
# Dial-in prefixes
international_prefixes = {
'FR': "33", # France
'AU': "61", # Australia
'NZ': "64", # New Zealand
'UK': "44", # United Kingdon
'US': "1", # United States
'CA': "1", # Canada
'CN': "86", # China
'JP': "81", # Japan
'PH': "63", # Philippines
'SG': "65", # Singapore
'ES': "34", # Spain
'TH': "66", # Thailand
'TR': "90", # Turkey
'AE': "971", # UAE
}
# Dial-out prefixes
international_call_prefix_itu = "^(00).*$"
international_call_prefix_regexs = {
'FR': international_call_prefix_itu,
'AU': "^(001[14589]).*$",
'NZ': international_call_prefix_itu,
'UK': international_call_prefix_itu,
'US': "^(0[1]{1,2}).*$",
'CA': "^(0[1]{1,2}).*$",
'CN': international_call_prefix_itu,
'JP': "^(001).*$",
'PH': international_call_prefix_itu,
'SG': "^(^|)(000|001|002|008|011|013|018|019|020|021).*$",
'ES': international_call_prefix_itu,
'TH': "^(001).*$",
'TR': international_call_prefix_itu,
'AE': international_call_prefix_itu,
}
''' Accepts a domestic or international phone number and the country in which it is valid,
and generalises that number to the international standard E.164 "+" format, compatible
with various SMS gateways.
Works in some countries. I only had to deal with a few in this instance, but this approach
should be easily extendible.
'''
def internationalise_number(number, country):
# Are we dealing with an international number, relative to the country?
icp = re.compile(international_call_prefix_regexs[country])
icp_code = icp.match(number)
is_international = (icp_code != None)
# Remove ICP if present.
if is_international:
icp_code = icp_code.group(1)
number = number[len(icp_code):]
# Remove trunk prefix if we're looking at a domestic number.
else:
if (country != "US" and country != "CA") and number[0] == '0':
number = number[1:]
elif (country == "US" or country == "CA") and number[0] == '1':
number = number[1:]
# Remove separators
number = number.replace('-','').replace(' ', '')
# Add country code if necessary
if number[0] == '+':
return number
if is_international:
return "+" + number
else:
return "+" + international_prefixes[country] + number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment