+81が付いた国際電話番号を国内電話番号へ変換したいと思い、
成功したので、ブログへ残します。
海外の電話番号も変換したかったので、大抵の国は対応しています。
import phonenumbers
def Phon_num_check(num):
print(len(str(num)))
country_list = ['JP', 'CN', 'IN', 'US', 'ID', 'PK', 'BR', 'NG', 'BD', 'RU', 'MX', 'PH', 'ET', 'EG', 'VN', 'DE', 'IR', 'TR', 'CD', 'TH', 'FR', 'GB', 'IT', 'ZA', 'MM', 'KE', 'KR', 'CO', 'ES', 'UA', 'TZ', 'AR', 'UG', 'PL', 'CA', 'AF', 'MY', 'MA', 'PE', 'UZ', 'VE', 'SA', 'GH', 'YE', 'NP', 'MM', 'KR', 'JP', 'NG', 'BD', 'RU', 'MX', 'PH', 'VN', 'ET', 'EG', 'DE', 'TR', 'TH', 'GB', 'FR', 'IT', 'MM', 'ZA', 'KE', 'CO', 'ES', 'UA', 'AR', 'TZ', 'UG', 'PL', 'AF', 'CA', 'MA', 'UZ', 'PE', 'VE', 'MY', 'GH', 'YE', 'NP', 'MM', 'SA', 'AU', 'CI', 'CM', 'MM', 'KE', 'SD', 'UA', 'UG', 'DZ', 'PL', 'CA', 'MA', 'AF', 'MY', 'UZ', 'VE', 'PE', 'GH', 'MM', 'NP', 'CI', 'CM', 'SD', 'AU']
for i in country_list:
phone_number = phonenumbers.parse(num, i)
if phonenumbers.is_valid_number(phone_number):
return phonenumbers.format_number(phonenumbers.parse(num, i), phonenumbers.PhoneNumberFormat.NATIONAL).replace(' ', '').replace('-', '').replace('(', '').replace(')', '')
else:pass
return ""
print(Phon_num_check('+818012345678'))
print(Phon_num_check('+819054321234'))
print(Phon_num_check('+447123456789'))
print(Phon_num_check('+12122223333'))
print(Phon_num_check('+447123456789'))
printの部分は、動作確認用です。
「.replace(' ', '').replace('-', '').replace('(', '').replace(')', '')」
この部分は、無くても動作はしますが、phonenumbersライブラリが勝手に記号やスペースを記入してくるので削除しています
国コードをfor文で探し出し、有効な番号があれば値を返しますが
有効な電話番号が見つからなければ、空文字「""」を返します
ただ、上記のコードは元の電話番号が数字のみの場合は正しく動作しますが
日本語やアルファベット等、電話番号に使わない文字が含まれると正常に動作しませんので
数字以外を削除する修正をしたものは、以下になります
import phonenumbers
import re
def Phon_num_check(num):
pattern = re.compile(r'[^\d]+')
num = re.sub(pattern, '', num)
if len(str(num)) > 9:
country_list = ['JP', 'CN', 'IN', 'US', 'ID', 'PK', 'BR', 'NG', 'BD', 'RU', 'MX', 'PH', 'ET', 'EG', 'VN', 'DE', 'IR', 'TR', 'CD', 'TH', 'FR', 'GB', 'IT', 'ZA', 'MM', 'KE', 'KR', 'CO', 'ES', 'UA', 'TZ', 'AR', 'UG', 'PL', 'CA', 'AF', 'MY', 'MA', 'PE', 'UZ', 'VE', 'SA', 'GH', 'YE', 'NP', 'MM', 'KR', 'JP', 'NG', 'BD', 'RU', 'MX', 'PH', 'VN', 'ET', 'EG', 'DE', 'TR', 'TH', 'GB', 'FR', 'IT', 'MM', 'ZA', 'KE', 'CO', 'ES', 'UA', 'AR', 'TZ', 'UG', 'PL', 'AF', 'CA', 'MA', 'UZ', 'PE', 'VE', 'MY', 'GH', 'YE', 'NP', 'MM', 'SA', 'AU', 'CI', 'CM', 'MM', 'KE', 'SD', 'UA', 'UG', 'DZ', 'PL', 'CA', 'MA', 'AF', 'MY', 'UZ', 'VE', 'PE', 'GH', 'MM', 'NP', 'CI', 'CM', 'SD', 'AU']
for i in country_list:
phone_number = phonenumbers.parse(num, i)
if phonenumbers.is_valid_number(phone_number):
return re.sub(pattern, '', phonenumbers.format_number(phonenumbers.parse(num, i), phonenumbers.PhoneNumberFormat.NATIONAL))
else:pass
return ""
環境
Python 3.10.6