forked from daviddrysdale/python-phonenumbers
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphonenumberutil.py
More file actions
2265 lines (1935 loc) · 101 KB
/
Copy pathphonenumberutil.py
File metadata and controls
2265 lines (1935 loc) · 101 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Python phone number parsing and formatting library
If you use this library, and want to be notified about important changes,
please sign up to the libphonenumber mailing list at
http://groups.google.com/group/libphonenumber-discuss/about.
NOTE: A lot of methods in this module require Region Code strings. These must
be provided using ISO 3166-1 two-letter country-code format. These should be
in upper-case. The list of the codes can be found here:
http://www.iso.org/iso/english_country_names_and_code_elements
author: Shaopeng Jia (original Java version)
author: Lara Rennie (original Java Version)
author: David Drysdale (Python version)
"""
# Based on original Java code:
# java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
# Copyright (C) 2009-2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from re_util import fullmatch # Extra regexp function; see README
import unicode_util
# Data class definitions
from phonenumber import PhoneNumber, CountryCodeSource
from phonemetadata import NumberFormat, PhoneMetadata
# Import auto-generated data structures
try:
from data import _COUNTRY_CODE_TO_REGION_CODE
except ImportError: # pragma no cover
# Before the generated code exists, the data/ directory is empty.
# The generation process imports this module, creating a circular
# dependency. The hack below works around this.
import os
import sys
if os.path.basename(sys.argv[0]) == "buildmetadatafromxml.py":
print >> sys.stderr, "Failed to import generated data (but OK as during autogeneration)"
_COUNTRY_CODE_TO_REGION_CODE = {1: ("US",)}
else:
raise
# Set the master map from country code to region code. The
# extra level of indirection allows the unit test to replace
# the map with test data.
COUNTRY_CODE_TO_REGION_CODE = _COUNTRY_CODE_TO_REGION_CODE
# Naming convention for phone number arguments and variables:
# - string arguments are named 'number'
# - PhoneNumber objects are named 'numobj'
# Flags to use when compiling regular expressions for phone numbers.
_REGEX_FLAGS = re.UNICODE | re.IGNORECASE
# The minimum and maximum length of the national significant number.
_MIN_LENGTH_FOR_NSN = 3
_MAX_LENGTH_FOR_NSN = 15
# The maximum length of the country calling code.
_MAX_LENGTH_COUNTRY_CODE = 3
# Region-code for the unknown region.
UNKNOWN_REGION = u"ZZ"
# The set of regions that share country calling code 1.
_NANPA_COUNTRY_CODE = 1
# The PLUS_SIGN signifies the international prefix.
_PLUS_SIGN = u'+'
_RFC3966_EXTN_PREFIX = u";ext="
# Simple ASCII digits map used to populate _ALPHA_PHONE_MAPPINGS and
# _ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
_ASCII_DIGITS_MAP = {u'0': u'0', u'1': u'1',
u'2': u'2', u'3': u'3',
u'4': u'4', u'5': u'5',
u'6': u'6', u'7': u'7',
u'8': u'8', u'9': u'9'}
# Only upper-case variants of alpha characters are stored.
_ALPHA_MAPPINGS = {u'A': u'2',
u'B': u'2',
u'C': u'2',
u'D': u'3',
u'E': u'3',
u'F': u'3',
u'G': u'4',
u'H': u'4',
u'I': u'4',
u'J': u'5',
u'K': u'5',
u'L': u'5',
u'M': u'6',
u'N': u'6',
u'O': u'6',
u'P': u'7',
u'Q': u'7',
u'R': u'7',
u'S': u'7',
u'T': u'8',
u'U': u'8',
u'V': u'8',
u'W': u'9',
u'X': u'9',
u'Y': u'9',
u'Z': u'9', }
# For performance reasons, amalgamate both into one map.
_ALPHA_PHONE_MAPPINGS = dict(_ALPHA_MAPPINGS, **_ASCII_DIGITS_MAP)
# Separate map of all symbols that we wish to retain when formatting alpha
# numbers. This includes digits, ASCII letters and number grouping symbols
# such as "-" and " ".
_ALL_PLUS_NUMBER_GROUPING_SYMBOLS = dict({u'-': u'-', # Put grouping symbols.
u'\uFF0D': u'-',
u'\u2010': u'-',
u'\u2011': u'-',
u'\u2012': u'-',
u'\u2013': u'-',
u'\u2014': u'-',
u'\u2015': u'-',
u'\u2212': u'-',
u'/': u'/',
u'\uFF0F': u'/',
u' ': u' ',
u'\u3000': u' ',
u'\u2060': u' ',
u'.': u'.',
u'\uFF0E': u'.'},
# Put (lower letter -> upper letter) and
# (upper letter -> upper letter) mappings.
**dict([(_c.lower(), _c) for _c in _ALPHA_MAPPINGS.keys()] +
[(_c, _c) for _c in _ALPHA_MAPPINGS.keys()],
**_ASCII_DIGITS_MAP))
# Pattern that makes it easy to distinguish whether a region has a unique
# international dialing prefix or not. If a region has a unique international
# prefix (e.g. 011 in USA), it will be represented as a string that contains a
# sequence of ASCII digits. If there are multiple available international
# prefixes in a region, they will be represented as a regex string that always
# contains character(s) other than ASCII digits. Note this regex also
# includes tilde, which signals waiting for the tone.
_UNIQUE_INTERNATIONAL_PREFIX = re.compile(u"[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?")
# Regular expression of acceptable punctuation found in phone numbers. This
# excludes punctuation found as a leading character only. This consists of
# dash characters, white space characters, full stops, slashes, square
# brackets, parentheses and tildes. It also includes the letter 'x' as that is
# found as a placeholder for carrier information in some phone numbers. Full-width
# variants are also present.
_VALID_PUNCTUATION = (u"-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
u"\u00A0\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E")
_DIGITS = '\\d' # Java "\\p{Nd}", so need "(?u)" or re.UNICODE wherever this is used
# We accept alpha characters in phone numbers, ASCII only, upper and lower
# case.
_VALID_ALPHA = (''.join(_ALPHA_MAPPINGS.keys()) +
''.join([_k.lower() for _k in _ALPHA_MAPPINGS.keys()]))
_PLUS_CHARS = u"+\uFF0B"
_PLUS_CHARS_PATTERN = re.compile(u"[" + _PLUS_CHARS + u"]+")
_SEPARATOR_PATTERN = re.compile(u"[" + _VALID_PUNCTUATION + u"]+")
_CAPTURING_DIGIT_PATTERN = re.compile(u"(" + _DIGITS + u")", re.UNICODE)
# Regular expression of acceptable characters that may start a phone number
# for the purposes of parsing. This allows us to strip away meaningless
# prefixes to phone numbers that may be mistakenly given to us. This consists
# of digits, the plus symbol and arabic-indic digits. This does not contain
# alpha characters, although they may be used later in the number. It also
# does not include other punctuation, as this will be stripped later during
# parsing and is of no information value when parsing a number.
_VALID_START_CHAR = u"[" + _PLUS_CHARS + _DIGITS + u"]"
_VALID_START_CHAR_PATTERN = re.compile(_VALID_START_CHAR, re.UNICODE)
# Regular expression of characters typically used to start a second phone
# number for the purposes of parsing. This allows us to strip off parts of the
# number that are actually the start of another number, such as for: (530)
# 583-6985 x302/x2303 -> the second extension here makes this actually two
# phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the
# second extension so that the first number is parsed correctly.
_SECOND_NUMBER_START = u"[\\\\/] *x"
_SECOND_NUMBER_START_PATTERN = re.compile(_SECOND_NUMBER_START)
# Regular expression of trailing characters that we want to remove. We remove
# all characters that are not alpha or numerical characters. The hash
# character is retained here, as it may signify the previous block was an
# extension.
#
# The original Java regexp is:
# [[\\P{N}&&\\P{L}]&&[^#]]+$
# which splits out as:
# [ ]+$ : >=1 of the following chars at end of string
# [ ]&&[ ] : intersection of these two sets of chars
# [ && ] : intersection of these two sets of chars
# \\P{N} : characters without the "Number" Unicode property
# \\P{L} : characters without the "Letter" Unicode property
# [^#] : character other than hash
# which nets down to: >=1 non-Number, non-Letter, non-# characters at string end
# In Python Unicode regexp mode '(?u)', the class '[^#\w]' will match anything
# that is not # and is not alphanumeric and is not underscore.
_UNWANTED_END_CHARS = '(?u)(?:_|[^#\w])+$'
_UNWANTED_END_CHAR_PATTERN = re.compile(_UNWANTED_END_CHARS)
# We use this pattern to check if the phone number has at least three letters
# in it - if so, then we treat it as a number where some phone-number digits
# are represented by letters.
_VALID_ALPHA_PHONE_PATTERN = re.compile(u"(?:.*?[A-Za-z]){3}.*")
# Regular expression of viable phone numbers. This is location
# independent. Checks we have at least three leading digits, and only valid
# punctuation, alpha characters and digits in the phone number. Does not
# include extension data. The symbol 'x' is allowed here as valid punctuation
# since it is often used as a placeholder for carrier codes, for example in
# Brazilian phone numbers. We also allow multiple "+" characters at the start.
# Corresponds to the following:
# plus_sign*([punctuation]*[digits]){3,}([punctuation]|[digits]|[alpha])*
# Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
_VALID_PHONE_NUMBER = (u"[" + _PLUS_CHARS + u"]*(?:[" + _VALID_PUNCTUATION + u"]*" + _DIGITS + u"){3,}[" +
_VALID_PUNCTUATION + _VALID_ALPHA + _DIGITS + u"]*")
# Default extension prefix to use when formatting. This will be put in front
# of any extension component of the number, after the main national number is
# formatted. For example, if you wish the default extension formatting to be
# " extn: 3456", then you should specify " extn: " here as the default
# extension prefix. This can be overridden by region-specific preferences.
_DEFAULT_EXTN_PREFIX = u" ext. "
# Regexp of all possible ways to write extensions, for use when parsing. This
# will be run as a case-insensitive regexp match. Wide character versions are
# also provided after each ASCII version. There are three regular expressions
# here. The first covers RFC 3966 format, where the extension is added using
# ";ext=". The second more generic one starts with optional white space and
# ends with an optional full stop (.), followed by zero or more spaces/tabs
# and then the numbers themselves. The other one covers the special case of
# American numbers where the extension is written with a hash at the end, such
# as "- 503#". Note that the only capturing groups should be around the
# digits that you want to capture as part of the extension, or else parsing
# will fail! Canonical-equivalence doesn't seem to be an option with Android
# java, so we allow two options for representing the accented o - the
# character itself, and one in the unicode decomposed form with the combining
# acute accent.
_CAPTURING_EXTN_DIGITS = u"(" + _DIGITS + u"{1,7})"
_KNOWN_EXTN_PATTERNS = (_RFC3966_EXTN_PREFIX + _CAPTURING_EXTN_DIGITS + u"|" +
u"[ \u00A0\\t,]*(?:ext(?:ensi(?:o\u0301?|\u00F3))?n?|" +
u"\uFF45\uFF58\uFF54\uFF4E?|[,x\uFF58#\uFF03~\uFF5E]|int|anexo|\uFF49\uFF4E\uFF54)" +
u"[:\\.\uFF0E]?[ \u00A0\\t,-]*" + _CAPTURING_EXTN_DIGITS + u"#?|" +
u"[- ]+(" + _DIGITS + u"{1,5})#")
# Regexp of all known extension prefixes used by different regions followed by
# 1 or more valid digits, for use when parsing.
_EXTN_PATTERN = re.compile(u"(?:" + _KNOWN_EXTN_PATTERNS + u")$", _REGEX_FLAGS)
# We append optionally the extension pattern to the end here, as a valid phone
# number may have an extension prefix appended, followed by 1 or more digits.
_VALID_PHONE_NUMBER_PATTERN = re.compile(_VALID_PHONE_NUMBER + u"(?:" + _KNOWN_EXTN_PATTERNS + u")?", _REGEX_FLAGS)
# We use a non-capturing group because Python's re.split() returns any capturing
# groups interspersed with the other results (unlike Java's Pattern.split()).
_NON_DIGITS_PATTERN = re.compile("(?:\\D+)")
# The FIRST_GROUP_PATTERN was originally set to \1 but there are some
# countries for which the first group is not used in the national pattern
# (e.g. Argentina) so the \1 group does not match correctly. Therefore, we
# use \d, so that the first group actually used in the pattern will be
# matched.
_FIRST_GROUP_PATTERN = re.compile(r"(\\\d)")
_NP_PATTERN = re.compile("\\$NP")
_FG_PATTERN = re.compile("\\$FG")
_CC_PATTERN = re.compile("\\$CC")
class PhoneNumberFormat(object):
"""
Phone number format.
INTERNATIONAL and NATIONAL formats are consistent with the definition in
ITU-T Recommendation E123. For example, the number of the Google
Switzerland office will be written as "+41 44 668 1800" in INTERNATIONAL
format, and as "044 668 1800" in NATIONAL format. E164 format is as per
INTERNATIONAL format but with no formatting applied, e.g. +41446681800.
RFC3966 is as per INTERNATIONAL format, but with all spaces and other
separating symbols replaced with a hyphen, and with any phone number
extension appended with ";ext=".
Note: If you are considering storing the number in a neutral format, you
are highly advised to use the PhoneNumber class.
"""
E164 = 0
INTERNATIONAL = 1
NATIONAL = 2
RFC3966 = 3
class PhoneNumberType(object):
"""Type of phone numbers."""
FIXED_LINE = 0
MOBILE = 1
# In some regions (e.g. the USA), it is impossible to distinguish between
# fixed-line and mobile numbers by looking at the phone number itself.
FIXED_LINE_OR_MOBILE = 2
# Freephone lines
TOLL_FREE = 3
PREMIUM_RATE = 4
# The cost of this call is shared between the caller and the recipient,
# and is hence typically less than PREMIUM_RATE calls. See
# http://en.wikipedia.org/wiki/Shared_Cost_Service for more information.
SHARED_COST = 5
# Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
VOIP = 6
# A personal number is associated with a particular person, and may be
# routed to either a MOBILE or FIXED_LINE number. Some more information
# can be found here: http://en.wikipedia.org/wiki/Personal_Numbers
PERSONAL_NUMBER = 7
PAGER = 8
# Used for "Universal Access Numbers" or "Company Numbers". They may be
# further routed to specific offices, but allow one number to be used for
# a company.
UAN = 9
# A phone number is of type UNKNOWN when it does not fit any of the known
# patterns for a specific region.
UNKNOWN = 10
class MatchType(object):
"""Types of phone number matches."""
# Not a telephone number
NOT_A_NUMBER = 0
# None of the match types below apply
NO_MATCH = 1
# Returns SHORT_NSN_MATCH if either or both has no region specified, or
# the region specified is the same, and one NSN could be a shorter version
# of the other number. This includes the case where one has an extension
# specified, and the other does not.
SHORT_NSN_MATCH = 2
# Either or both has no region specified, and the NSNs and extensions are
# the same.
NSN_MATCH = 3
# The country_code, NSN, presence of a leading zero for Italian numbers
# and any extension present are the same.
EXACT_MATCH = 4
class ValidationResult(object):
"""Possible outcomes when testing if a PhoneNumber is a possible number."""
IS_POSSIBLE = 0
INVALID_COUNTRY_CODE = 1
TOO_SHORT = 2
TOO_LONG = 3
# Derived data structures
SUPPORTED_REGIONS = set([_item for _sublist in COUNTRY_CODE_TO_REGION_CODE.values() for _item in _sublist])
_NANPA_REGIONS = set(COUNTRY_CODE_TO_REGION_CODE[_NANPA_COUNTRY_CODE])
def _extract_possible_number(number):
"""Attempt to extract a possible number from the string passed in.
This currently strips all leading characters that cannot be used to
start a phone number. Characters that can be used to start a phone number
are defined in the VALID_START_CHAR_PATTERN. If none of these characters
are found in the number passed in, an empty string is returned. This
function also attempts to strip off any alternative extensions or endings
if two or more are present, such as in the case of: (530) 583-6985
x302/x2303. The second extension here makes this actually two phone
numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the
second extension so that the first number is parsed correctly.
Arguments:
number -- The string that might contain a phone number.
Returns the number, stripped of any non-phone-number prefix (such
as "Tel:") or an empty string if no character used to start phone
numbers (such as + or any digit) is found in the number
"""
match = _VALID_START_CHAR_PATTERN.search(number)
if match:
number = number[match.start():]
# Remove trailing non-alpha non-numberical characters.
trailing_chars_match = _UNWANTED_END_CHAR_PATTERN.search(number)
if trailing_chars_match:
number = number[:trailing_chars_match.start()]
# Check for extra numbers at the end.
second_number_match = _SECOND_NUMBER_START_PATTERN.search(number)
if second_number_match:
number = number[:second_number_match.start()]
return number
else:
return u""
def _is_viable_phone_number(number):
"""Checks to see if a string could possibly be a phone number.
At the moment, checks to see that the string begins with at least 3
digits, ignoring any punctuation commonly found in phone numbers. This
method does not require the number to be normalized in advance - but does
assume that leading non-number symbols have been removed, such as by the
method _extract_possible_number.
Arguments:
number -- string to be checked for viability as a phone number
Returns True if the number could be a phone number of some sort, otherwise
False
"""
if len(number) < _MIN_LENGTH_FOR_NSN:
return False
match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number)
return bool(match)
def _normalize(number):
"""Normalizes a string of characters representing a phone number.
This performs the following conversions:
- Punctuation is stripped.
- For ALPHA/VANITY numbers:
- Letters are converted to their numeric representation on a telephone
keypad. The keypad used here is the one defined in ITU
Recommendation E.161. This is only done if there are 3 or more
letters in the number, to lessen the risk that such letters are
typos - otherwise alpha characters are stripped.
- For other numbers:
- Wide-ascii digits are converted to normal ASCII (European) digits.
- Arabic-Indic numerals are converted to European numerals.
- Spurious alpha characters are stripped.
Arguments:
number -- string representing a phone number
Returns the normalized string version of the phone number.
"""
m = fullmatch(_VALID_ALPHA_PHONE_PATTERN, number)
if m:
return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, True)
else:
return normalize_digits_only(number)
def normalize_digits_only(number):
"""Normalizes a string of characters representing a phone number.
This converts wide-ascii and arabic-indic numerals to European numerals,
and strips punctuation and alpha characters.
Arguments:
number -- a string representing a phone number
Returns the normalized string version of the phone number.
"""
number = unicode(number)
number_length = len(number)
normalized_digits = u""
for ii in xrange(number_length):
d = unicode_util.digit(number[ii], -1)
if d != -1:
normalized_digits += unicode(d)
return normalized_digits
def convert_alpha_characters_in_number(number):
"""Convert alpha chars in a number to their respective digits on a keypad,
but retains existing formatting."""
return _normalize_helper(number, _ALPHA_PHONE_MAPPINGS, False)
def length_of_geographical_area_code(numobj):
"""Return length of the geographical area code for a number.
Gets the length of the geographical area code in the national_number
field of the PhoneNumber object passed in, so that clients could use it to
split a national significant number into geographical area code and
subscriber number. It works in such a way that the resultant subscriber
number should be diallable, at least on some devices. An example of how
this could be used:
>>> import phonenumbers
>>> numobj = phonenumbers.parse("16502530000", "US")
>>> nsn = phonenumbers.national_significant_number(numobj)
>>> ac_len = phonenumbers.length_of_geographical_area_code(numobj)
>>> if ac_len > 0:
... area_code = nsn[:ac_len]
... subscriber_number = nsn[ac_len:]
... else:
... area_code = ""
... subscriber_number = nsn
N.B.: area code is a very ambiguous concept, so the I18N team generally
recommends against using it for most purposes, but recommends using the
more general national_number instead. Read the following carefully before
deciding to use this method:
- geographical area codes change over time, and this method honors those
changes; therefore, it doesn't guarantee the stability of the result it
produces.
- subscriber numbers may not be diallable from all devices (notably
mobile devices, which typically require the full national_number to be
dialled in most countries).
- most non-geographical numbers have no area codes.
- some geographical numbers have no area codes.
Arguments:
numobj -- The PhoneNumber object to find the length of the area code form.
Returns the length of area code of the PhoneNumber object passed in.
"""
region_code = region_code_for_number(numobj)
if not _is_valid_region_code(region_code):
return 0
metadata = PhoneMetadata.region_metadata[region_code]
if metadata.national_prefix is None:
return 0
pn_type = _number_type_helper(national_significant_number(numobj),
metadata)
# Most numbers other than the two types below have to be dialled in full.
if (pn_type != PhoneNumberType.FIXED_LINE and
pn_type != PhoneNumberType.FIXED_LINE_OR_MOBILE):
return 0
return length_of_national_destination_code(numobj)
def length_of_national_destination_code(numobj):
"""Return length of the national destination code code for a number.
Gets the length of the national destination code (NDC) from the
PhoneNumber object passed in, so that clients could use it to split a
national significant number into NDC and subscriber number. The NDC of a
phone number is normally the first group of digit(s) right after the
country calling code when the number is formatted in the international
format, if there is a subscriber number part that follows. An example of
how this could be used:
>>> import phonenumbers
>>> numobj = phonenumbers.parse("18002530000", "US")
>>> nsn = phonenumbers.national_significant_number(numobj)
>>> ndc_len = phonenumbers.length_of_national_destination_code(numobj)
>>> if ndc_len > 0:
... national_destination_code = nsn[:ndc_len]
... subscriber_number = nsn[ndc_len:]
... else:
... national_destination_code = ""
... subscriber_number = nsn
Refer to the unittests to see the difference between this function and
length_of_geographical_area_code.
Arguments:
numobj -- The PhoneNumber object to find the length of the NDC from.
Returns the length of NDC of the PhoneNumber object passed in.
"""
if numobj.extension is not None:
# We don't want to alter the object given to us, but we don't want to
# include the extension when we format it, so we copy it and clear the
# extension here.
copied_numobj = PhoneNumber()
copied_numobj.merge_from(numobj)
copied_numobj.extension = None
else:
copied_numobj = numobj
nsn = format_number(copied_numobj, PhoneNumberFormat.INTERNATIONAL)
number_groups = re.split(_NON_DIGITS_PATTERN, nsn)
# The pattern will start with "+COUNTRY_CODE " so the first group will
# always be the empty string (before the + symbol) and the second group
# will be the country calling code. The third group will be area code if
# it is not the last group.
if len(number_groups) <= 3:
return 0
if (region_code_for_number(numobj) == "AR" and
number_type(numobj) == PhoneNumberType.MOBILE):
# Argentinian mobile numbers, when formatted in the international
# format, are in the form of +54 9 NDC XXXX... As a result, we take the
# length of the third group (NDC) and add 1 for the digit 9, which also
# forms part of the national significant number.
#
# TODO: Investigate the possibility of better modeling the metadata to
# make it easier to obtain the NDC.
return len(number_groups[3]) + 1
return len(number_groups[2])
def _normalize_helper(number, replacements, remove_non_matches):
"""Normalizes a string of characters representing a phone number by
replacing all characters found in the accompanying map with the values
therein, and stripping all other characters if remove_non_matches is true.
Arguments:
number -- a string representing a phone number
replacements -- a mapping of characters to what they should be replaced
by in the normalized version of the phone number
remove_non_matches -- indicates whether characters that are not able to be
replaced should be stripped from the number. If this is False,
they will be left unchanged in the number.
Returns the normalized string version of the phone number.
"""
normalized_number = []
for char in number:
new_digit = replacements.get(char.upper(), None)
if new_digit is not None:
normalized_number.append(new_digit)
elif not remove_non_matches:
normalized_number.append(char)
# If neither of the above are true, we remove this character
return u''.join(normalized_number)
def _is_valid_region_code(region_code):
"""Helper function to check region code is not unknown or None"""
if region_code is None:
return False
return (region_code in SUPPORTED_REGIONS)
def format_number(numobj, num_format):
"""Formats a phone number in the specified format using default rules.
Note that this does not promise to produce a phone number that the user
can dial from where they are - although we do format in either 'national'
or 'international' format depending on what the client asks for, we do not
currently support a more abbreviated format, such as for users in the same
"area" who could potentially dial the number without area code. Note that
if the phone number has a country calling code of 0 or an otherwise
invalid country calling code, we cannot work out which formatting rules to
apply so we return the national significant number with no formatting
applied.
Arguments:
numobj -- The phone number to be formatted.
num_format -- The format the phone number should be formatted into
Returns the formatted phone number.
"""
country_calling_code = numobj.country_code
nsn = national_significant_number(numobj)
if num_format == PhoneNumberFormat.E164:
# Early exit for E164 case since no formatting of the national number needs to be applied.
# Extensions are not formatted.
return _format_number_by_format(country_calling_code, num_format, nsn)
# Note region_code_for_country_code() is used because formatting
# information for regions which share a country calling code is contained
# by only one region for performance reasons. For example, for NANPA
# regions it will be contained in the metadata for US.
region_code = region_code_for_country_code(country_calling_code)
if not _is_valid_region_code(region_code):
return nsn
formatted_number = _format_national_number(nsn, region_code, num_format)
formatted_number = _maybe_get_formatted_extension(numobj,
region_code,
num_format,
formatted_number)
return _format_number_by_format(country_calling_code,
num_format,
formatted_number)
def format_by_pattern(numobj, num_format, user_defined_formats):
"""Formats a phone number using client-defined formatting rules."
Note that if the phone number has a country calling code of zero or an
otherwise invalid country calling code, we cannot work out things like
whether there should be a national prefix applied, or how to format
extensions, so we return the national significant number with no
formatting applied.
Arguments:
numobj -- The phone number to be formatted
num_format -- The format the phone number should be formatted into
user_defined_formats -- formatting rules specified by clients
Returns the formatted phone number.
"""
country_code = numobj.country_code
nsn = national_significant_number(numobj)
# Note region_code_for_country_code() is used because formatting
# information for regions which share a country calling code is contained
# by only one region for performance reasons. For example, for NANPA
# regions it will be contained in the metadata for US.
region_code = region_code_for_country_code(country_code)
if not _is_valid_region_code(region_code):
return nsn
user_defined_formats_copy = []
for this_format in user_defined_formats:
np_formatting_rule = this_format.national_prefix_formatting_rule
if (np_formatting_rule is not None and len(np_formatting_rule) > 0):
# Before we do a replacement of the national prefix pattern $NP
# with the national prefix, we need to copy the rule so that
# subsequent replacements for different numbers have the
# appropriate national prefix.
this_format_copy = NumberFormat()
this_format_copy.merge_from(this_format)
metadata = PhoneMetadata.region_metadata[region_code]
national_prefix = metadata.national_prefix
if (national_prefix is not None and len(national_prefix) > 0):
# Replace $NP with national prefix and $FG with the first
# group (\1) matcher.
np_formatting_rule = re.sub(_NP_PATTERN,
national_prefix,
np_formatting_rule,
count=1)
np_formatting_rule = re.sub(_FG_PATTERN,
u"\\\\1",
np_formatting_rule,
count=1)
this_format_copy.national_prefix_formatting_rule = np_formatting_rule
else:
# We don't want to have a rule for how to format the national
# prefix if there isn't one.
this_format_copy.national_prefix_formatting_rule = None
user_defined_formats_copy.append(this_format_copy)
else:
# Otherwise, we just add the original rule to the modified list of
# formats.
user_defined_formats_copy.append(this_format)
formatted_number = _format_according_to_formats(nsn,
user_defined_formats_copy,
num_format)
formatted_number = _maybe_get_formatted_extension(numobj,
region_code,
num_format,
formatted_number)
formatted_number = _format_number_by_format(country_code,
num_format,
formatted_number)
return formatted_number
def format_national_number_with_carrier_code(numobj, carrier_code):
"""Format a number in national format for dialing using the specified carrier.
The carrier-code will always be used regardless of whether the phone
number already has a preferred domestic carrier code stored. If
carrier_code contains an empty string, returns the number in national
format without any carrier code.
Arguments:
numobj -- The phone number to be formatted
carrier_code -- The carrier selection code to be used
Returns the formatted phone number in national format for dialing using
the carrier as specified in the carrier_code.
"""
country_code = numobj.country_code
nsn = national_significant_number(numobj)
# Note region_code_for_country_code() is used because formatting
# information for regions which share a country calling code is contained
# by only one region for performance reasons. For example, for NANPA
# regions it will be contained in the metadata for US.
region_code = region_code_for_country_code(country_code)
if not _is_valid_region_code(region_code):
return nsn
formatted_number = _format_national_number(nsn,
region_code,
PhoneNumberFormat.NATIONAL,
carrier_code)
formatted_number = _maybe_get_formatted_extension(numobj,
region_code,
PhoneNumberFormat.NATIONAL,
formatted_number)
formatted_number = _format_number_by_format(country_code,
PhoneNumberFormat.NATIONAL,
formatted_number)
return formatted_number
def format_national_number_with_preferred_carrier_code(numobj, fallback_carrier_code):
"""Formats a phone number in national format for dialing using the carrier
as specified in the preferred_domestic_carrier_code field of the
PhoneNumber object passed in. If that is missing, use the
fallback_carrier_code passed in instead. If there is no
preferred_domestic_carrier_code, and the fallback_carrier_code contains an
empty string, return the number in national format without any carrier
code.
Use format_national_number_with_carrier_code instead if the carrier code
passed in should take precedence over the number's
preferred_domestic_carrier_code when formatting.
Arguments:
numobj -- The phone number to be formatted
carrier_code -- The carrier selection code to be used, if none is found in the
phone number itself.
Returns the formatted phone number in national format for dialing using
the number's preferred_domestic_carrier_code, or the fallback_carrier_code
pass in if none is found.
"""
if numobj.preferred_domestic_carrier_code is not None:
carrier_code = numobj.preferred_domestic_carrier_code
else:
carrier_code = fallback_carrier_code
return format_national_number_with_carrier_code(numobj, carrier_code)
def format_out_of_country_calling_number(numobj, region_calling_from):
"""Formats a phone number for out-of-country dialing purposes.
If no region_calling_from is supplied, we format the number in its
INTERNATIONAL format. If the country calling code is the same as that of
the region where the number is from, then NATIONAL formatting will be
applied.
If the number itself has a country calling code of zero or an otherwise
invalid country calling code, then we return the number with no formatting
applied.
Note this function takes care of the case for calling inside of NANPA and
between Russia and Kazakhstan (who share the same country calling
code). In those cases, no international prefix is used. For regions which
have multiple international prefixes, the number in its INTERNATIONAL
format will be returned instead.
Arguments:
numobj -- The phone number to be formatted
region_calling_from -- The region where the call is being placed
Returns the formatted phone number
"""
if not _is_valid_region_code(region_calling_from):
return format_number(numobj, PhoneNumberFormat.INTERNATIONAL)
country_code = numobj.country_code
region_code = region_code_for_country_code(country_code)
nsn = national_significant_number(numobj)
if not _is_valid_region_code(region_code):
return nsn
if country_code == _NANPA_COUNTRY_CODE:
if is_nanpa_country(region_calling_from):
# For NANPA regions, return the national format for these regions
# but prefix it with the country calling code.
return (unicode(country_code) + u" " +
format_number(numobj, PhoneNumberFormat.NATIONAL))
elif country_code == country_code_for_region(region_calling_from):
# For regions that share a country calling code, the country calling
# code need not be dialled. This also applies when dialling within a
# region, so this if clause covers both these cases. Technically this
# is the case for dialling from La Reunion to other overseas
# departments of France (French Guiana, Martinique, Guadeloupe), but
# not vice versa - so we don't cover this edge case for now and for
# those cases return the version including country calling code.
# Details here:
# http://www.petitfute.com/voyage/225-info-pratiques-reunion
return format_number(numobj, PhoneNumberFormat.NATIONAL)
formatted_national_number = _format_national_number(nsn,
region_code,
PhoneNumberFormat.INTERNATIONAL)
metadata = PhoneMetadata.region_metadata[region_calling_from.upper()]
international_prefix = metadata.international_prefix
# For regions that have multiple international prefixes, the international
# format of the number is returned, unless there is a preferred
# international prefix.
i18n_prefix_for_formatting = u""
i18n_match = fullmatch(_UNIQUE_INTERNATIONAL_PREFIX, international_prefix)
if i18n_match:
i18n_prefix_for_formatting = international_prefix
elif metadata.preferred_international_prefix is not None:
i18n_prefix_for_formatting = metadata.preferred_international_prefix
formatted_number = _maybe_get_formatted_extension(numobj,
region_code,
PhoneNumberFormat.INTERNATIONAL,
formatted_national_number)
if len(i18n_prefix_for_formatting) > 0:
formatted_number = (i18n_prefix_for_formatting + u" " +
unicode(country_code) + u" " + formatted_number)
else:
formatted_number = _format_number_by_format(country_code,
PhoneNumberFormat.INTERNATIONAL,
formatted_number)
return formatted_number
def format_in_original_format(numobj, region_calling_from):
"""Format a number using the original format that the number was parsed from.
The original format is embedded in the country_code_source field of the
PhoneNumber object passed in. If such information is missing, the number
will be formatted into the NATIONAL format by default.
Arguments:
number -- The phone number that needs to be formatted in its original
number format
region_calling_from -- The region whose IDD needs to be prefixed if the
original number has one.
Returns the formatted phone number in its original number format.
"""
if numobj.country_code_source is None:
return format_number(numobj, PhoneNumberFormat.NATIONAL)
if (numobj.country_code_source ==
CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN):
return format_number(numobj, PhoneNumberFormat.INTERNATIONAL)
elif numobj.country_code_source == CountryCodeSource.FROM_NUMBER_WITH_IDD:
return format_out_of_country_calling_number(numobj, region_calling_from)
elif (numobj.country_code_source ==
CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN):
return format_number(numobj, PhoneNumberFormat.INTERNATIONAL)[1:]
else:
return format_number(numobj, PhoneNumberFormat.NATIONAL)
def format_out_of_country_keeping_alpha_chars(numobj, region_calling_from):
"""Formats a phone number for out-of-country dialing purposes.
Note that in this version, if the number was entered originally using
alpha characters and this version of the number is stored in raw_input,
this representation of the number will be used rather than the digit
representation. Grouping information, as specified by characters such as
"-" and " ", will be retained.
Caveats:
- This will not produce good results if the country calling code is both
present in the raw input _and_ is the start of the national
number. This is not a problem in the regions which typically use alpha
numbers.
- This will also not produce good results if the raw input has any
grouping information within the first three digits of the national
number, and if the function needs to strip preceding digits/words in
the raw input before these digits. Normally people group the first
three digits together so this is not a huge problem - and will be fixed
if it proves to be so.
Arguments:
numobj -- The phone number that needs to be formatted.
region_calling_from -- The region where the call is being placed.
Returns the formatted phone number
"""
raw_input = numobj.raw_input
# If there is no raw input, then we can't keep alpha characters because there aren't any.
# In this case, we return format_out_of_country_calling_number.
if raw_input is None or len(raw_input) == 0:
return format_out_of_country_calling_number(numobj, region_calling_from)
country_code = numobj.country_code
region_code = region_code_for_country_code(country_code)
if not _is_valid_region_code(region_code):
return raw_input
# Strip any prefix such as country calling code, IDD, that was present. We
# do this by comparing the number in raw_input with the parsed number. To
# do this, first we normalize punctuation. We retain number grouping
# symbols such as " " only.
raw_input = _normalize_helper(raw_input,
_ALL_PLUS_NUMBER_GROUPING_SYMBOLS,
True)
# Now we trim everything before the first three digits in the parsed
# number. We choose three because all valid alpha numbers have 3 digits at
# the start - if it does not, then we don't trim anything at
# all. Similarly, if the national number was less than three digits, we
# don't trim anything at all.
national_number = national_significant_number(numobj)
if len(national_number) > 3:
first_national_number_digit = raw_input.find(national_number[:3])
if first_national_number_digit != -1:
raw_input = raw_input[first_national_number_digit:]
metadata = PhoneMetadata.region_metadata.get(region_calling_from.upper(), None)
if country_code == _NANPA_COUNTRY_CODE:
if is_nanpa_country(region_calling_from):
return unicode(country_code) + u" " + raw_input
elif country_code == country_code_for_region(region_calling_from):
# Here we copy the formatting rules so we can modify the pattern we
# expect to match against.
available_formats = []
for this_format in metadata.number_format:
new_format = NumberFormat()
new_format.merge_from(this_format)
# The first group is the first group of digits that the user
# determined.
new_format.pattern = u"(\\d+)(.*)"
# Here we just concatenate them back together after the national
# prefix has been fixed.
new_format.format = ur"\1\2"
available_formats.append(new_format)
# Now we format using these patterns instead of the default pattern,
# but with the national prefix prefixed if necessary, by choosing the
# format rule based on the leading digits present in the unformatted
# national number. This will not work in the cases where the pattern
# (and not the leading digits) decide whether a national prefix needs
# to be used, since we have overridden the pattern to match anything,