PyXR

c:\projects\bitpim\src \ phonenumber.py



0001 ### BITPIM
0002 ###
0003 ### Copyright (C) 2004 Roger Binns <rogerb@rogerbinns.com>
0004 ###
0005 ### This program is free software; you can redistribute it and/or modify
0006 ### it under the terms of the BitPim license as detailed in the LICENSE file.
0007 ###
0008 ### $Id: phonenumber.py 4404 2007-09-23 03:27:27Z djpham $
0009 
0010 """Code for normalising and formatting phone numbers
0011 
0012 This doesn't (yet) try to deal with international numbers.
0013 The rule is that if the string contains 10 digits (with an optional
0014 preceding one) then it is reduced to the 10 digits (all non-digit
0015 characters removed, optional leading one removed).
0016 
0017 If the string doesn't meet those criteria then it is passed through
0018 as is.
0019 
0020 For formatting, 10 digit strings are formatted in standard US
0021 notation.  All others are left as is.
0022 """
0023 
0024 
0025 import re
0026 
0027 _notdigits=re.compile("[^0-9]*")
0028 _tendigits=re.compile("^[0-9]{10}$")
0029 _sevendigits=re.compile("^[0-9]{7}$")
0030 
0031 
0032 def normalise(n):
0033     # this was meant to remove the long distance '1' prefix,
0034     # temporary disable it, will be done on a phone-by-phone case.
0035     return n
0036     nums="".join(re.split(_notdigits, n))
0037     if len(nums)==10:
0038         return nums
0039     if len(nums)==11 and nums[0]=="1":
0040         return nums[1:]
0041     return n
0042 
0043 def format(n):
0044     if re.match(_tendigits, n) is not None:
0045         return "(%s) %s-%s" % (n[0:3], n[3:6], n[6:])
0046     elif re.match(_sevendigits, n) is not None:
0047         return "%s-%s" %(n[:3], n[3:])
0048     return n
0049 
0050 
0051 if __name__=='__main__':
0052     nums=("011441223518046", "+1-123-456-7890", "(123) 456-7890", "0041-2702885504",
0053           "19175551212", "9175551212", "123 456 7890", "123 456 7890 ext 17")
0054 
0055     for n in nums:
0056         print "%s\n  norm: %s\n   fmt: %s\n" % (n, normalise(n), format(normalise(n)))
0057 

Generated by PyXR 0.9.4