当前位置:
编程学习 >
python >>
用Python实现查询手机号码归属地实用代码
用Python实现手机号码归属查询代码
- Python 2.6.2 (r262:71600, Aug 4 2009, 09:26:47)
- [GCC 3.4.6 20060404 (Red Hat 3.4.6-10)] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> from PhoneRegion import getRegion,loadRegion
- >>> numsdb = loadRegion()
- >>> print getRegion(1234123,numsdb)
- 未知,未知
- >>> print getRegion(15213492123,numsdb)
- 未知,未知
- >>> print getRegion(13213492123,numsdb)
- 河南濮阳,联通130卡
- >>> print getRegion(13513492123,numsdb)
- 河北沧州,移动全球通卡
- #!/usr/bin/env python
- # -*- coding=utf-8 -*-
- import re
- import sys
- import gzip
- numberRe = re.compile(^1[0-9]{10}$)
- numsDbRe = re.compile((^1[0-9]{6}) (.*) (.*))
- def getRegion(number,numsDb):
- if not numberRe.search(number):
- return 未知,未知
- if not numsDb:
- return 未知,未知
- k = number[0:3]
- v = number[3:7]
- if not k in numsDb:
- return 未知,未知
- else:
- region = numsDb[k].get(v,(未知,未知))
- return ,.join(region)
- def loadRegion():
- RegionDb = {}
- try:
- for line in gzip.open(numsdb.tar.gz).readlines():
- line = line.strip()
- m = numsDbRe.search(line)
- if m:
- nums,area,card = m.groups()
- k = nums[0:3]
- v = nums[3:7]
- if k in RegionDb:
- RegionDb[k][v] = (area,card)
- else:
- RegionDb[k]={}
- RegionDb[k][v] = (area,card)
- return RegionDb
- except Exception,e:
- print e
- return {}
- if __name__ == __main__:
- numsDb = loadRegion()
- try:
- number = sys.argv[1]
- print number,getRegion(number,numsDb)
- except:
- pass
补充:Web开发 , Python ,