import re
class IDCardChecker:
def __init__(self, card_num):
self.card_num = card_num
#返回性别
def get_gender(self):
gender_num = int(self.card_num[-2])
if not self.is_valid():
return '不是合法的中国公民身份证号码'
if gender_num % 2 == 0:
return '女'
else:
return '男'
#返回出生日期
def get_birthday(self):
if self.is_valid():
return self.card_num[6:14]
else:
return '不是合法的中国公民身份证号码'
#返回身份证是否合法
def is_valid(self):
regex = r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$'
# 匹配正则表达式
if not re.match(regex, self.card_num):
return False
if(len(self.card_num)!=18):
return False
weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
sum_num = 0
for i in range(17):
sum_num += int(self.card_num[i]) * weight[i]
check_num = check_code[sum_num % 11]
if check_num == self.card_num[-1]:
return True
else:
return False
#返回身份证对应的身份(省份)
def get_province(self):
province_code = {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: '澳门', 91: '国外'}
if self.is_valid():
return province_code[int(self.card_num[:2])]
else:
return '不是合法的中国公民身份证号码'
#使用
id_card = IDCardChecker('420102199001011234')
print(id_card.get_gender()) # 输出:男
print(id_card.get_birthday()) # 输出:19990908
print(id_card.is_valid()) # 输出:False
print(id_card.get_province()) # 输出:北京