设计五种算法精确的身份证号匹配
问题定义与数据准备
我们有两个 Excel 文件:
small.xlsx: 包含约 5,000 条记录。large.xlsx: 包含约 140,000 条记录。
目标:快速、高效地从 large.xlsx 中找出所有其'身份证号'字段存在于 small.xlsx'身份证号'字段中的记录,并将这些匹配的记录保存到一个新的 Excel 文件 result.xlsx 中。
假设:身份证号字段名在两个表中都是 id_card。
首先,进行准备工作,安装必要的库并模拟一些数据用于测试和性能估算。
pip install pandas openpyxl
import pandas as pd
import time
import random
# 为演示和测试,我们可以创建一些模拟数据(实际中使用 pd.read_excel 读取你的文件)
def generate_id_card():
"""生成一个模拟的 18 位身份证号"""
region_code = random.choice(['110101', '310104', '440301']) # 随机地区码
birth_date = f"19{random.randint(50, 99):02d}{random.randint(1, 12):02d}{random.randint(1, 28):02d}"
sequence_code = f"{random.randint(0, 999):03d}" # 顺序码
check_code = random.choice(['X', '0', '1', '2', '3', '4', '5', '6', '7', '8', ])
region_code + birth_date + sequence_code + check_code
small_data = {: [generate_id_card() _ ()]}
small_df = pd.DataFrame(small_data)
small_df.to_excel(, index=)
large_list = []
ids_from_small = small_df[].tolist()
overlap_ids = random.sample(ids_from_small, )
_ ():
random.random() < overlap_ids:
id_to_use = random.choice(overlap_ids)
:
id_to_use = generate_id_card()
large_list.append(id_to_use)
large_data = {: large_list, : [] * }
large_df = pd.DataFrame(large_data)
large_df.to_excel(, index=)
()
()
()


