1. 程式人生 > >隨機獲取身份證和手機號

隨機獲取身份證和手機號

因為最近輸入框需要輸入手機號和身份證號,網上搜了個範本出來,方便以後隨機生成(還有一個districtcode.txt不知道怎麼上傳)

# coding:utf-8
import random
import os
import datetime

PATH_DIR = os.path.dirname(os.path.realpath(__file__))
ID_PATH =  os.path.join(PATH_DIR, "districtcode.txt")

"隨機產生電話號碼"
def randomPhoneNum():
    numlist=["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(numlist)+"".join(random.choice("0123456789") for i in range(8))

def randomStr(num):
    seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"
    sa = []
    for i in range(num):
        sa.append(random.choice(seed))
    salt = ''.join(sa)
    print salt

"隨機產生身份證號碼"
def getdistrictcode():
  with open(ID_PATH) as file:
    data = file.read()
    districtlist = data.split('\n')
  for node in districtlist:
    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 randomID():
  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

if __name__ == "__main__":
    print "手機號:",randomPhoneNum()
    print "身份證號:",randomID()