Module phonenumber
[hide private]
[frames] | no frames]

Source Code for Module phonenumber

 1  ### BITPIM 
 2  ### 
 3  ### Copyright (C) 2004 Roger Binns <rogerb@rogerbinns.com> 
 4  ### 
 5  ### This program is free software; you can redistribute it and/or modify 
 6  ### it under the terms of the BitPim license as detailed in the LICENSE file. 
 7  ### 
 8  ### $Id: phonenumber.py 4404 2007-09-23 03:27:27Z djpham $ 
 9   
10  """Code for normalising and formatting phone numbers 
11   
12  This doesn't (yet) try to deal with international numbers. 
13  The rule is that if the string contains 10 digits (with an optional 
14  preceding one) then it is reduced to the 10 digits (all non-digit 
15  characters removed, optional leading one removed). 
16   
17  If the string doesn't meet those criteria then it is passed through 
18  as is. 
19   
20  For formatting, 10 digit strings are formatted in standard US 
21  notation.  All others are left as is. 
22  """ 
23   
24   
25  import re 
26   
27  _notdigits=re.compile("[^0-9]*") 
28  _tendigits=re.compile("^[0-9]{10}$") 
29  _sevendigits=re.compile("^[0-9]{7}$") 
30   
31   
32 -def normalise(n):
33 # this was meant to remove the long distance '1' prefix, 34 # temporary disable it, will be done on a phone-by-phone case. 35 return n 36 nums="".join(re.split(_notdigits, n)) 37 if len(nums)==10: 38 return nums 39 if len(nums)==11 and nums[0]=="1": 40 return nums[1:] 41 return n
42
43 -def format(n):
44 if re.match(_tendigits, n) is not None: 45 return "(%s) %s-%s" % (n[0:3], n[3:6], n[6:]) 46 elif re.match(_sevendigits, n) is not None: 47 return "%s-%s" %(n[:3], n[3:]) 48 return n
49 50 51 if __name__=='__main__': 52 nums=("011441223518046", "+1-123-456-7890", "(123) 456-7890", "0041-2702885504", 53 "19175551212", "9175551212", "123 456 7890", "123 456 7890 ext 17") 54 55 for n in nums: 56 print "%s\n norm: %s\n fmt: %s\n" % (n, normalise(n), format(normalise(n))) 57