chinapnr / fishbase

自主开发、整理的一套 Python 基础函数库,涵盖 system 系统增强包、logger 日志记录增强包、file 文件处理增强包、 date 日期处理函数包、data 数据信息处理函数包、csv 处理增强函数包、crypt 加密/编码增强包等,可减少程序开发工作量、降低引用复杂度。
MIT License
94 stars 29 forks source link

fish_data, 计算身份证校验码 #143

Closed wingfish closed 5 years ago

wingfish commented 5 years ago

将计算身份证校验码函数单独提炼,命名为 get_idcard_checkcode() 输入:17位身份证号码 输出:校验码

itaa commented 5 years ago

定义 flag 为 False 时的 checkcode 为 -1

if not re.match(id_regex, id_number_str):
    return False, -1
wingfish commented 5 years ago

目前代码实现如下:


# 计算身份证号码的校验位
# ---
# 2018.12.12 create by David.Yi, add in v1.1.4 github issue #143
def get_idcard_checkcode(id_number_str):
    """
    计算身份证号码的校验位;

    :param:
        * id_number_str: (string) 身份证号的前17位,比如 3201241987010100
    :returns:
        * 返回类型 (tuple)
        * flag: (bool) 如果身份证号格式正确,返回 True;格式错误,返回 False
        * checkcode: 计算身份证前17位的校验码

    举例如下::

        from fishbase.fish_data import *

        print('--- fish_data get_idcard_checkcode demo ---')

        # id number
        id1 = '32012419870101001'
        print(id1, get_idcard_checkcode(id1)[1])

        # id number
        id2 = '13052219840731647'
        print(id2, get_idcard_checkcode(id2)[1])

        print('---')

    输出结果::
        --- fish_data get_idcard_checkcode demo ---
        32012419870101001 5
        13052219840731647 1
        ---

    """

    # 判断长度,如果不是 17 位,直接返回失败
    if len(id_number_str) != 17:
        return False, -1

    id_regex = '[1-9][0-9]{14}([0-9]{2}[0-9X])?'

    if not re.match(id_regex, id_number_str):
        return False, -1

    items = [int(item) for item in id_number_str]

    # 加权因子表
    factors = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)

    # 计算17位数字各位数字与对应的加权因子的乘积
    copulas = sum([a * b for a, b in zip(factors, items)])

    # 校验码表
    check_codes = ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')

    checkcode = check_codes[copulas % 11].upper()

    return True, checkcode
wingfish commented 5 years ago

单元测试完成

    def test_get_idcard_checkcode(self):
        # id number <= 17
        id1 = '32012419870101'
        assert get_idcard_checkcode(id1)[0] is False
        id1 = '320124198701010012'
        assert get_idcard_checkcode(id1)[0] is False

        # id number checkcode
        id1 = '22068119870103456'
        assert get_idcard_checkcode(id1)[1] == '0'

        id1 = '62010519941220163'
        assert get_idcard_checkcode(id1)[1] != '2'  # is 9