python 身份证工具

介绍:

       可以解析身份证,获取身份证的省,市,区信息,年龄,性别,生日信息

import re
from datetime import datetime
import json

class IDCardParserUtil:

    def __init__(self):
        pass

    # 身份证号码前6位对应省市区编码
    id_card_area_codes = {

    }

    @staticmethod
    def parseIdCard(id_card):
        # 从文件加载身份证号码前6位对应省市区编码
        with open('../files/id_card_area_codes.json', 'r', encoding='utf-8') as f:
            IDCardParserUtil.id_card_area_codes =json.load(f)
        # 定义身份证号码的正则表达式模式
        pattern = r'^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$'

        # 使用正则表达式匹配身份证号码
        if not re.match(pattern, id_card):
            raise ValueError("身份证号码格式不正确 id_card: "+id_card)

        # 提取前6位作为省市区编码
        area_code = id_card[:6]
        province = IDCardParserUtil.id_card_area_codes.get(area_code[:2] + '0000', '未知')
        city = IDCardParserUtil.id_card_area_codes.get(area_code[:4] + '00', '未知')
        district = IDCardParserUtil.id_card_area_codes.get(area_code, '未知')

        # 提取出生日期部分
        birth_year = int(id_card[6:10])
        birth_month = int(id_card[10:12])
        birth_day = int(id_card[12:14])
        birth_date = datetime(birth_year, birth_month, birth_day).strftime('%Y-%m-%d')

        # 提取性别
        gender_code = int(id_card[16:17])
        gender = '男' if gender_code % 2 != 0 else '女'

     # 计算年龄
        today = datetime.today()
        age = today.year - birth_year - ((today.month, today.day) < (birth_month, birth_day))

        return {
            'province': province,
            'city': city,
            'district': district,
            'birth_date': birth_date,
            'birth_year': birth_year,
            'birth_month': birth_month,
            'birth_day': birth_day,
            'gender': gender,
            'age': age
        }

if __name__ == '__main__':

    # 示例身份证号码
    id_card = "11010519980801007X"

    try:
        result = IDCardParserUtil.parseIdCard(id_card)
        print(result)
    except ValueError as e:
        print(e)

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值