Python实现随机生成有效手机号码及身份证功能示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现随机生成有效手机号码及身份证功能。分享给大家供大家参考,具体如下:

中国那么大,人那么多,几乎人手一部手机。手机号码已经作为各大互联网站的注册账户。同样,身份证更是如此。以下是生成有效手机号码和身份证号。

身份证需要下载districtcode.txt文件

完整代码如下:

import os
import random
import datetime
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DC_PATH = BASE_DIR + "districtcode.txt"
# 随机生成手机号码
def createPhone():
 prelist=["130","131","132","133","134","135","136","137","138","139","147","150","151","152","153","155","156","157","158","159","186","187","188"]
 return random.choice(prelist)+"".join(random.choice("0123456789") for i in range(8))
# 随机生成身份证号
def getdistrictcode(): 
 with open(DC_PATH) as file: 
  data = file.read() 
  districtlist = data.split('\n') 
 for node in districtlist: 
 #print node 
  if node[10:11] != ' ': 
   state = node[10:].strip() 
  if node[10:11]==' 'and node[12:13]!=' ': 
   city = node[12:].strip() 
  if node[10:11] == ' 'and node[12:13]==' ': 
   district = node[14:].strip() 
   code = node[0:6] 
   codelist.append({"state":state,"city":city,"district":district,"code":code})
def gennerator(): 
 global codelist 
 codelist = [] 
 if not codelist:
  getdistrictcode()
 id = codelist[random.randint(0,len(codelist))]['code'] #地区项 
 id = id + str(random.randint(1930,2013)) #年份项 
 da = datetime.date.today()+datetime.timedelta(days=random.randint(1,366)) #月份和日期项 
 id = id + da.strftime('%m%d') 
 id = id+ str(random.randint(100,300))#,顺序号简单处理 
 i = 0
 count = 0
 weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] #权重项 
 checkcode ={'0':'1','1':'0','2':'X','3':'9','4':'8','5':'7','6':'6','7':'5','8':'5','9':'3','10':'2'} #校验码映射 
 for i in range(0,len(id)): 
  count = count +int(id[i])*weight[i] 
  id = id + checkcode[str(count%11)] #算出校验码 
  return id
print createPhone()
print gennerator()

运行结果如下:

PS:这里再提供一款本站身份证归属地信息查询工具供大家参考:

身份证归属地信息在线查询:
http://tools.jb51.net/bianmin/sfz

另外,本站在线工具小程序上也有一款功能更加强大的身份证信息获取工具,感兴趣的朋友可以扫描如下小程序码查看:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python字符串操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

用Python实现将一张图片分成9宫格的示例

用Python实现将一张图片分成9宫格的示例

经常看到朋友圈或者空间里有朋友发布照片时,将朋友圈的照片切分为九宫格,参考了一些大神的博客资料,现整理如下; 将图片分拆成九宫格的思路: 读取图片->填充图片为正方形(fill_i...

Python自定义一个异常类的方法

Python自定义一个异常类的方法

如何实现自定义一个异常 python内置了许多异常类,为编写代码划定红线,才使调试代码时能及时发现错误。那么我们编写一个模块也可以为使用此模块者划定红线,来约束使用者可用哪些数据,这就需...

Python 执行字符串表达式函数(eval exec execfile)

仔细研读后学习了三个函数: eval:计算字符串中的表达式 exec:执行字符串中的语句 execfile:用来执行一个文件 需注意的是,exec是一个语句,而eval()和execfi...

利用python实现数据分析

1:文件内容格式为json的数据如何解析 import json,os,sys current_dir=os.path.abspath(".") filename=[file f...

Python多线程扫描端口代码示例

本文代码实现Python多线程扫描端口,具体实现代码如下。 #coding:utf-8 import socket import thread import time socket....