本帖最后由 gdyabc 于 2017-7-26 23:58 编辑
[Python] 纯文本查看 复制代码 #-*- encoding:utf-8 -*-
import sys
import os
import string
import datetime
#以前一直用VB6/VB.NET现刚接触Python不到一个星期,练手先了解数据类型,编码格式,字符串处理,文件读写等初级用法.
#Python(3.5)
def Verify_ID(code):
try:
if len(code) != 18:
print(code + ' :编码位数不正确')
os._exit(0)
else:
if not code[:-1].isdigit():
print(code + ' :编码格式不正确,前17位不能包含字符必须为数字.')
os._exit(0)
else:
lstExp = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1] #加权因子
lstValid = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2] #校验码
xsum = 0
for i in range(17):
xsum += int(code) * lstExp #前17位数字与权值乘积相加求合
idx = xsum % 11 #算余数为模
if code[17].upper() == lstValid[idx]: #第18位是否与校验码对应
Analysis_ID(code)
return True
else:
print(code + ' : 不符合中国大陆18位身份证.')
return False
except Exception as err:
print(err)
def Analysis_ID(code):
_address = str(code[:6])
_byear = int(code[6:10])
_bmonth = str(code[10:12])
_bday = int(code[12:14])
_today = datetime.date.today().year
_m = int(code[16])
if _m % 2 == 0:
_six = '女'
else:
_six = '男'
_agv = _today - int(_byear)
print('编码: ' + code + ' | 出生年月: ' + '%s年%s月%s日' % (_byear, _bmonth, _bday) +
' | 年龄: ' + str(_agv) + ' | 性别: ' + _six + ' | 地址: ' + dic[_address])
try:
fileurl = os.getcwd() + '\\ID_Data.txt'
if not os.path.exists(fileurl):
print('Data file is missing.')
os._exit(0)
else:
dic = {}
f = open(fileurl, 'r')
strbuff = f.readlines()
for s in strbuff:
strtemp = s.strip().split(',')
dic[strtemp[0]] = strtemp[1]
f.close()
except Exception as err:
print(err)
xID = '123456789123456789'
verifyResult = Verify_ID(xID)
print(verifyResult) |