用python语句1.读取教师提供的[政区代码. xml] 文件,获取行政区代码表;2.把身份证号按照字符串类型进行处理,根据对应位的子串查找行政区代码表,推导出生地省、市、县区,再把倒数第二位字符转化为整数类型,根据其奇偶性判别男女性别;3.根据网上公开的C语言身份证号合法性验证算法,写出更高效的Python函数。
时间: 2023-06-02 11:05:15 浏览: 97
1. 读取教师提供的[政区代码.xml]文件,获取行政区代码表可以使用Python的ElementTree模块来解析xml文件,示例代码如下:
```python
import xml.etree.ElementTree as ET
tree = ET.parse('政区代码.xml')
root = tree.getroot()
# 遍历xml文件的节点,获取行政区代码表
for province in root:
province_code = province.attrib['code']
for city in province:
city_code = city.attrib['code']
for county in city:
county_code = county.attrib['code']
```
2. 把身份证号按照字符串类型进行处理,根据对应位的子串查找行政区代码表,推导出生地省、市、县区,再把倒数第二位字符转化为整数类型,根据其奇偶性判断男女性别可以使用正则表达式来匹配身份证号码格式,然后根据对应位的子串在行政区代码表中查找生地省、市、县区,示例代码如下:
```python
import re
def get_identity_info(id_card_num):
id_card_num = str(id_card_num)
# 匹配身份证号的正则表达式
pattern = r'^\d{17}(\d|x)$'
if not re.match(pattern, id_card_num):
raise ValueError('身份证号格式错误')
# 根据身份证号中的前6位查找行政区代码表,获取生地省、市
province_code = id_card_num[:2] + '0000'
city_code = id_card_num[:4] + '00'
# 从行政区代码表中获取生地省、市
province = ''
city = ''
county = ''
for child in root:
if child.attrib['code'] == province_code:
province = child.attrib['name']
for grandchild in child:
if grandchild.attrib['code'] == city_code:
city = grandchild.attrib['name']
break
break
# 根据身份证号中的前6位和后四位查找行政区代码表,获取生地县区
county_code = id_card_num[:6] + id_card_num[-4:]
for child in root:
for grandchild in child:
for greatgrandchild in grandchild:
if greatgrandchild.attrib['code'] == county_code:
county = greatgrandchild.attrib['name']
break
# 根据身份证号中的倒数第二位判断性别
gender = int(id_card_num[-2])
gender = '男' if gender % 2 == 1 else '女'
# 返回身份证号对应的身份信息
return province, city, county, gender
```
3. 根据网上公开的C语言身份证号合法性验证算法,写出更高效的Python函数可以使用Python的内置函数divmod来做除法和取模运算,示例代码如下:
```python
def validate_id_card(id_card_num):
# 身份证校验系数
factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
# 校验码对应关系,最后一位是校验码
codes = '10X98765432'
# 判断身份证号码格式是否正确
id_card_num = str(id_card_num)
pattern = r'^\d{17}(\d|x)$'
if not re.match(pattern, id_card_num):
return False
# 计算身份证号的校验码
sum = 0
for i in range(17):
sum += int(id_card_num[i]) * factors[i]
remainder = divmod(sum, 11)[1]
check_code = codes[remainder]
# 手动将小写字母x转为大写字母X
if id_card_num[-1].upper() != check_code:
return False
# 身份证号码校验通过
return True
```
阅读全文