dongfangho 发表于 2015-12-1 09:49:43

Python 随机生成有效手机号码及身份证

  中国那么大,人那么多,几乎人手一部手机。手机号码已经作为各大互联网站的注册账户。同样,身份证更是如此。以下是生成有效手机号码和身份证号。
      身份证需要下载districtcode.txt这个文件:http://files.cnblogs.com/files/yicaifeitian/districtcode.rar



1 BASE_DIR = os.path.dirname(os.path.dirname(__file__))
2 DC_PATH = BASE_DIR+ "districtcode.txt"
3
4 # 随机生成手机号码
5 def createPhone():
6   prelist=["130","131","132","133","134","135","136","137","138","139","147","150","151","152","153","155","156","157","158","159","186","187","188"]
7   return random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))
8
9 # 随机生成身份证号
10 def getdistrictcode():
11   with open(DC_PATH) as file:
12         data = file.read()
13         districtlist = data.split('\n')
14   for node in districtlist:
15   #print node
16         if node != ' ':
17             state = node.strip()
18         if node==' 'and node!=' ':
19             city = node.strip()
20         if node == ' 'and node==' ':
21             district = node.strip()
22             code = node
23             codelist.append({"state":state,"city":city,"district":district,"code":code})
24
25 def gennerator():
26   global codelist
27   codelist = []
28   if not codelist:
29         getdistrictcode()
30   id = codelist['code'] #地区项
31   id = id + str(random.randint(1930,2013)) #年份项
32   da = date.today()+timedelta(days=random.randint(1,366)) #月份和日期项
33   id = id + da.strftime('%m%d')
34   id = id+ str(random.randint(100,300))#,顺序号简单处理
35   
36   i = 0
37   count = 0
38   weight = #权重项
39   checkcode ={'0':'1','1':'0','2':'X','3':'9','4':'8','5':'7','6':'6','7':'5','8':'5','9':'3','10':'2'} #校验码映射
40   for i in range(0,len(id)):
41         count = count +int(id)*weight
42         id = id + checkcode #算出校验码
43         return id
44
45 print createPhone()
46 print gennerator()
  
  
页: [1]
查看完整版本: Python 随机生成有效手机号码及身份证