欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

python 自动生成身份证

最编程 2024-05-05 07:23:16
...

Python 自动生成身份证

在日常开发过程中,我们有时需要生成虚拟的身份证号码,用于测试、模拟数据等目的。本文将介绍如何使用Python生成身份证号码,并提供相应的代码示例。

身份证号码的结构

中国的身份证号码是由18位数字和一个校验位组成的。它的结构如下所示:

  1. 前6位是地区码,表示发证机关的行政区划代码;
  2. 接下来8位是生日码,表示持证人的出生日期;
  3. 接下来3位是顺序码,表示同一地区、同一生日出生的人的顺序号;
  4. 最后1位是校验码,用于校验身份证号码的合法性。

生成身份证号码的算法

生成身份证号码的算法如下所示:

  1. 随机生成一个地区码;
  2. 随机生成一个生日码;
  3. 随机生成一个顺序码;
  4. 根据前面三个码计算出校验码。

代码示例

下面是使用Python生成身份证号码的示例代码:

import random

# 地区码
region_codes = ['110101', '110102', '110103', ...]

# 随机生成地区码
region_code = random.choice(region_codes)

# 随机生成生日码
year = random.randint(1900, 2022)
month = random.randint(1, 12)
day = random.randint(1, 28)
birthday_code = f"{year:04d}{month:02d}{day:02d}"

# 随机生成顺序码
sequence_code = random.randint(0, 999)

# 计算校验码
factors = [int(c) for c in f"{region_code}{birthday_code}{sequence_code:03d}"]
weights = [int(w) for w in "7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2".split()]
check_code = sum([f * w for f, w in zip(factors, weights)]) % 11
check_code = '10X98765432'[check_code]

# 生成身份证号码
id_number = f"{region_code}{birthday_code}{sequence_code:03d}{check_code}"
print(id_number)

上述代码中,我们首先定义了一个地区码的列表 region_codes,包含了一些常见的地区码。然后,通过 random.choice() 函数从地区码列表中随机选择一个地区码。接着,我们使用 random.randint() 函数生成一个随机的生日码,并使用字符串格式化将其转换为4位年份、2位月份和2位日期的字符串。然后,我们使用 random.randint() 函数生成一个3位的顺序码。最后,我们使用校验算法计算出校验码,并将所有码拼接起来生成身份证号码。最后,我们通过 print() 函数将生成的身份证号码输出。

使用范例

下面是使用生成身份证号码的范例代码:

import random

def generate_id_number():
    region_codes = ['110101', '110102', '110103', ...]
    region_code = random.choice(region_codes)
  
    year = random.randint(1900, 2022)
    month = random.randint(1, 12)
    day = random.randint(1, 28)
    birthday_code = f"{year:04d}{month:02d}{day:02d}"
  
    sequence_code = random.randint(0, 999)
  
    factors = [int(c) for c in f"{region_code}{birthday_code}{sequence_code:03d}"]
    weights = [int(w) for w in "7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2".split()]
    check_code = sum([f * w for f, w in zip(factors, weights)]) % 11
    check_code = '10X98765432'[check_code]
  
    return f"{region_code}{birthday_code}{sequence_code:03d}{check_code}"

# 生成10个身份证号码
id_numbers = [generate_id_number() for _ in range(10)]
print(id_numbers)

上述代码中,我们定义了一个名为 generate_id_number() 的函数,用于生成

上一篇: java 随机生成 10 个 ID 号

下一篇:

推荐阅读