zoukankan      html  css  js  c++  java
  • faker类库--解析身份证并写文件

    from faker import Faker
    import csv,datetime
    from pathlib import Path
    
    base_dir=Path.cwd()
    data_dir=base_dir/'test_data'
    faker=Faker(locale='zh-CN')
    
    class GetIDCardInfo():
        def __init__(self,tcardID):
            self.tcardID = tcardID
            self.birth_year = int(self.tcardID[6:10])
            self.birth_month = int(self.tcardID[10:12])
            self.birth_day = int(self.tcardID[12:14])
    
        def get_birthday(self):
            # 通过身份证取出生日,日期格式化输出,处理前导零的问题。':02d'
            # birthday = "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)
            # return birthday
            birthday = f"{self.birth_year}-{self.birth_month:02d}-{self.birth_day:02d}"
            return birthday
    
        def get_sex(self):
            # 男:1,女:0
            num = int(self.tcardID[16:17])
            if num % 2 == 0:
                return 0
            else:
                return 1
    
        def get_age(self):
            now = (datetime.datetime.now() + datetime.timedelta(days=1))
            year = now.year
            month = now.month
            day = now.day
    
            if year == self.birth_year:
                return 0
            else:
                if self.birth_month>month or (self.birth_month ==month and self.birth_day > day):
                    return year - self.birth_year - 1
                else:
                    return year - self.birth_year
    
    # # 调试段        
    # tcardID=faker.ssn(min_age=1, max_age=70)
    # print(tcardID)
    # tbirthday = GetIDCardInfo(tcardID).get_birthday()
    # print(tbirthday)
    
    # 构建数据并填写到csv文件,newline为另起一行去除空行
    with open(data_dir/'testdata2.csv','w',encoding='utf-8',newline='') as f:
        fwrite=csv.writer(f)
        for i in range(1,11):
            # 生成身份证
            tcardID=faker.ssn(min_age=18, max_age=80)
            print(tcardID)
            # 拆解身份证获取生日
            tbirthday = GetIDCardInfo(tcardID).get_birthday()
            print(tbirthday)
            # 获取性别
            tsex = GetIDCardInfo(tcardID).get_sex()
            # # 获取年龄
            # tage = GetIDCardInfo(tcardID).get_age()
            # 姓名
            tname=faker.name()
            # 电话
            ttel=faker.phone_number()
            # 地址
            taddress=faker.address()
    
            # 写入文件
            fwrite.writerow([tname,tcardID,ttel,tbirthday,tsex,taddress])
  • 相关阅读:
    蓝桥杯--芯片测试
    蓝桥杯--FJ的字符串
    win8 js 没反应
    winform win8 js checkbox互动
    win8 GridView
    wcf服务引用无实体类对象
    arcgis 接口转换与.Net框架
    win8 链接
    分页控件
    Oracle 分页查询存储过程
  • 原文地址:https://www.cnblogs.com/liuyi1804/p/15434047.html
Copyright © 2011-2022 走看看