介绍:
可以解析身份证,获取身份证的省,市,区信息,年龄,性别,生日信息
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)