基于Python的身份证校验及数据提取

根据GB11643-1999公民身份证号码是特征组合码,由十七位数字本体码和一位数字校验码组成,排列顺序从左至右依次为:

  1. 六位数字地址码
  2. 八位数字出生日期码
  3. 三位数字顺序码
  4. 一位数字校验码(数字10用罗马X表示)

校验系统:

     校验码采用ISO7064:1983,MOD11-2校验码系统(图为校验规则样例)

用身份证号的前17位的每一位号码字符值分别乘上对应的加权因子值,得到的结果求和后对11进行取余,最后的结果放到表2检验码字符值..换算关系表中得出最后的一位身份证号码

 代码:

import datetime


def return_ditu():
    path = 'C:/Users/2019/Desktop/身份证/行政划分.txt'
    f = open(path,'r', encoding="utf-8")
    dict_sheng = {}
    dict_shi = {}
    dict_diqu = {}
    dict_all = {}
    for sig in f.readlines():
        sig = sig.replace(" ","")
        sig = sig.replace("\n","")
        # print(sig[:6],sig[6:])
        if '000' in sig:
            # print("我是省和直辖市{}".format(sig[:-1]))
            dict_sheng[sig[:6]] = sig[6:]
        else:
            if '00' in sig:
                # print("我是市{}".format(sig[:-1]))
                dict_shi[sig[:6]] = sig[6:]
            else:
                # print("我是地区{}".format(sig[:-1]))
                dict_diqu[sig[:6]] = sig[6:]
    for i in dict_diqu:
       cahe_sheng= i[:-4]+'0000'
       cahe_shi = i[:-2]+'00'
       if cahe_shi in dict_shi:
           dict_all[i] = dict_sheng[cahe_sheng],dict_shi[cahe_shi],dict_diqu[i]
           # print(i,dict_sheng[cahe_sheng],dict_shi[cahe_shi],dict_diqu[i])
       else:
           dict_all[i] = dict_sheng[cahe_sheng],dict_diqu[i]
           # print(i,dict_sheng[cahe_sheng],dict_diqu[i])
    return dict_all

def get_where(id_card):
    where_id = id_card[:6]
    print("籍贯:",end=" ")
    print(area_id[where_id])

def check_where(id_card):
    where_id = id_card[:6]
    try:
        are = area_id[where_id]
        return 1
    except KeyError:
        return error_type[0]
        # print("找不到该地区或身份证前六位有误")

def get_birth(id_card):
    birth_id = id_card[6:14]
    print("出生日期:{}".format(birth_id))

def get_sex(id_card):
    sex_id = id_card[-2:-1]
    print("性别:  ",end=" ")
    if int(sex_id) % 2 == 0:
        print("女")
    else:
        print("男")

def get_tureorerror(id_card):
    sum = 0
    list_quan = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1]
    list_ture = [1,0,'X',9,8,7,6,5,4,3,2]
    for idx in range(0,len(list_quan)-1):
        cach = list_quan[idx]*int(id_card[idx])
        sum = sum + cach
    last = list_ture[sum % 11]
    if str(last) == id_card[-1:]:
        print("正确身份证")
        return error_type[4]
    else:
        return error_type[2]


def check_id_card(id_card):
    if len(id_card) != 18:
        print("长度错误")
        return error_type[3]
    else:
        try:
            res = datetime.datetime(int(id_card[6:10]), int(id_card[10:12]), int(id_card[12:14]))
        except ValueError:
            print("出生日期有误")
            return error_type[1]
        sig = check_where(id_card)
        if sig != 1:
            return sig
        else:
            return get_tureorerror(id_card)


if __name__ == '__main__':
    error_type = ['找不到该地区或身份证前六位错误', '出生日期错误', '身份证校验错误', '身份证长度错误','正确身份证']
    area_id = return_ditu()
    # id = '130828199807160612'
    id = input("请输入身份证号码:")
    res = check_id_card(id)
    if res == '正确身份证':
        get_where(id)
        get_sex(id)
        get_birth(id)
    else:
        print(res)



运行过程:

 使用说明:

运行前请先复制到行政规划到指定txt文件,并修改path中txt文件存放路径

行政规划链接:https://blog.csdn.net/qq_42006613/article/details/109625058

 

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
身份证号码共18位,其中前17位为地区和出生年月日信息,最后一位校验码。以下是基于python实现的身份证校验和信息提取: ```python import re def check_idcard(idcard): """ 身份证校验函数 """ # 校验身份证号码格式 if not re.match(r'^\d{17}(\d|X|x)$', idcard): return False # 校验身份证号码的前17位是否合法 province_code = idcard[:2] if province_code not in PROVINCE_CODE: return False birth_year = int(idcard[6:10]) birth_month = int(idcard[10:12]) birth_day = int(idcard[12:14]) if not is_valid_date(birth_year, birth_month, birth_day): return False # 校验身份证号码的最后一位是否正确 weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2] check_code = '10X98765432'[sum([int(idcard[i]) * weights[i] for i in range(17)]) % 11] if check_code != idcard[-1].upper(): return False return True def get_idcard_info(idcard): """ 身份证信息提取函数 """ province_code = idcard[:2] province = PROVINCE_DICT.get(province_code, '') birth_year = int(idcard[6:10]) birth_month = int(idcard[10:12]) birth_day = int(idcard[12:14]) sex = '女' if int(idcard[-2]) % 2 == 0 else '男' return { 'province': province, 'birth_year': birth_year, 'birth_month': birth_month, 'birth_day': birth_day, 'sex': sex } def is_valid_date(year, month, day): """ 判断日期是否合法 """ if month < 1 or month > 12: return False if day < 1 or day > 31: return False if month in [4, 6, 9, 11] and day > 30: return False if month == 2: if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: if day > 29: return False else: if day > 28: return False return True # 省份代和名称映射 PROVINCE_DICT = { '11': '北京市', '12': '天津市', '13': '河北省', '14': '山西省', '15': '内蒙古自治区', '21': '辽宁省', '22': '吉林省', '23': '黑龙江省', '31': '上海市', '32': '江苏省', '33': '浙江省', '34': '安徽省', '35': '福建省', '36': '江西省', '37': '山东省', '41': '河南省', '42': '湖北省', '43': '湖南省', '44': '广东省', '45': '广西壮族自治区', '46': '海南省', '50': '重庆市', '51': '四川省', '52': '贵州省', '53': '云南省', '54': '西藏自治区', '61': '陕西省', '62': '甘肃省', '63': '青海省', '64': '宁夏回族自治区', '65': '新疆维吾尔自治区', '71': '台湾省', '81': '香港特别行政区', '82': '澳门特别行政区' } # 省份代列表 PROVINCE_CODE = list(PROVINCE_DICT.keys()) ``` 使用示例: ```python idcard = '11010119900307401X' if check_idcard(idcard): idcard_info = get_idcard_info(idcard) print(idcard_info) else: print('身份证号码不合法') ``` 输出结果: ``` {'province': '北京市', 'birth_year': 1990, 'birth_month': 3, 'birth_day': 7, 'sex': '男'} ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值