美文网首页IT技术
2018-11-26 python 随机数据生成模块

2018-11-26 python 随机数据生成模块

作者: 昨天今天下雨天1 | 来源:发表于2018-11-26 14:46 被阅读0次
    # -*- coding: utf-8 -*-
    """一些生成器方法,生成随机数,手机号,以及连续数字等"""
    import random
    from faker import Factory
    
    # zh_CN 表示中国大陆版
    fake = Factory().create('zh_CN')
    
    
    def random_phone_number():
        # 随机手机号
        return fake.phone_number()
    
    
    def random_phone_number_xxx0000xxxx():
        return random_phone_number()[0:3] + '0000' + ''.join(random.choice("0123456789") for i in range(4))
        # 随机手机号 中间4位用0000替代
    
    def random_name():
        # 随机姓名
        return fake.name()
    
    
    def random_date():
        # 随机日期 yyyy-mm-dd
        return fake.date(pattern="%Y-%m-%d")
    
    
    def random_address():
        # 随机地址
        return fake.address()
    
    
    def random_email():
        # 随机email
        return fake.email()
    
    
    def random_company_name():
        # 随机公司名称
        return fake.company_name()
    
    
    def random_ipv4():
        # 随机IPV4地址
        return fake.ipv4()
    
    
    def random_str(min_chars=0, max_chars=8):
        # 长度在最大值与最小值之间的随机字符串
        return fake.pystr(min_chars=min_chars, max_chars=max_chars)
    
    
    def factory_generate_ids(starting_id=1, increment=1):
        """ Return function generator for ids starting at starting_id
            Note: needs to be called with () to make generator """
    
        def generate_started_ids():
            val = starting_id
            local_increment = increment
            while True:
                yield val
                val += local_increment
    
        return generate_started_ids
    
    
    def factory_choice_generator(values):
        """ Return a generator that picks values from a list randomly """
    
        def choice_generator():
            my_list = list(values)
            # rand = random.Random()
            while True:
                yield random.choice(my_list)
    
        return choice_generator
    
    
    if __name__ == '__main__':
        print(random_phone_number())
        print(random_phone_number_xxx0000xxxx())
        print(random_name())
        print(random_address())
        print(random_email())
        print(random_ipv4())
        print(random_str(min_chars=6, max_chars=8))
        id_gen = factory_generate_ids(starting_id=0, increment=2)()
        for i in range(5):
            print(next(id_gen))
    
        choices = ['John', 'Sam', 'Lily', 'Rose']
        choice_gen = factory_choice_generator(choices)()
        for i in range(5):
            print(next(choice_gen))
    
    

    相关文章

      网友评论

        本文标题:2018-11-26 python 随机数据生成模块

        本文链接:https://www.haomeiwen.com/subject/isjbqqtx.html