-
Notifications
You must be signed in to change notification settings - Fork 1
/
phone.py
72 lines (64 loc) · 2.42 KB
/
phone.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import logging
from typing import List, Optional
import phonenumbers
log = logging.getLogger(__name__)
def is_international_phone_number(phone_number: str) -> bool:
"""
Check if a phone number is international
:param phone_number: The phone number to check
:return: True if the phone number is international AND valid, False otherwise
"""
try:
parsed_phone_number = phonenumbers.parse(phone_number, "US")
# if the phone number is not valid, we can't be sure if it's international or not.
if not phonenumbers.is_valid_number(parsed_phone_number):
return False
return (
parsed_phone_number.country_code is not None
and parsed_phone_number.country_code != 1
)
except Exception as e:
log.warning(
f"Error checking if phone number {phone_number} is international because of {e}"
)
return False
def format_phone_number(phone_number: str) -> Optional[str]:
"""
Format a phone number to the US standard
:param phone_number: The phone number to format
:return: The formatted phone number
"""
try:
parsed_phone_number = phonenumbers.parse(phone_number, "US")
if not phonenumbers.is_valid_number(parsed_phone_number):
return None
if (
not parsed_phone_number.country_code
or parsed_phone_number.country_code == 1
):
return phonenumbers.format_number(
parsed_phone_number, phonenumbers.PhoneNumberFormat.NATIONAL
)
return phonenumbers.format_number(
parsed_phone_number, phonenumbers.PhoneNumberFormat.INTERNATIONAL
)
except Exception as e:
log.warning(
f"Error formatting phone number {phone_number} because of {e}"
)
return None
def extract_phone_numbers(text: str) -> List[str]:
"""
Extract and format all phone numbers from an unstructured blob of text.
This function will only extract **valid** phone numbers, so those with an incorrect area code,
or the wrong length will be ignored
:param text: A blob of text.
:return: A list of formatted phone numbers
"""
numbers = []
for match in phonenumbers.PhoneNumberMatcher(text, "US"):
number = phonenumbers.format_number(
match.number, phonenumbers.PhoneNumberFormat.NATIONAL
)
numbers.append(number)
return numbers