前言:
有些时候我们需要用到一些算法生成验证码/识别码,所以我尝试做了一个这样的生成库供各位同行参考,希望大家喜欢
艾诺德原创算法,未经允许严禁转载!!!
#-*-coding:utf-8-*-
import random
class VerificationCodeSystem:
'''
这个类是用来生成随机识别码(验证码)的
你可以通过修改基础长度以生成不同长度的识别码
'''
def __init__(self, normal_length = 6, used_codes = set()):
self.verification_codes = used_codes #已生成的识别码
self.normal_length = normal_length #决定生成识别码长度的变量
self.code_groups = {} #调用group方法后的组分类
def creat_code(self, difficult_value = 1, material = []):
'''
你可以用这个函数创建一个识别码
通过添加difficult_value你可以增加识别码难度系数
如果加了material,则所生成的识别码都基于material
'''
if material:
args = material
else :
args = []
arg = args.append
for number in range(10):
arg(str(number))
for upper_code in range(65, 91):
arg(chr(upper_code))
for lower_code in range(97, 123):
arg(chr(lower_code))
select_args = random.sample((args * difficult_value), self.normal_length)
code = "".join(select_args)
if not code in self.verification_codes:
if code:
self.verification_codes.add(code)
return code
else :
self.creat_code(difficult_value, material)
def prolong_length(self, length = 1):
'''
这个函数用于延长最大识别码长度
'''
self.normal_length += length
def group(self):
'''
这个函数用于以长度将识别码归类
'''
han_group = self.code_groups.get
for code in self.verification_codes:
group_name = str(len(code))
if not han_group(group_name):
self.code_groups[group_name] = []
self.code_groups[group_name].append(code)
def get_codes(self):
'''
这个函数允许获取所有已生成的识别码
'''
return self.verification_codes
def get_code_group(self, group_name = None):
'''
这个函数允许你获取单个长度组或所有长度组的识别码
'''
self.group()
if group_name:
return self.code_groups.setdefault(group_name, [])
else :
return self.code_groups
'''
下列代码对上述功能进行了一次测试
VerificationCodeSystem = VerificationCodeSystem(6)
i = 0
d = 1
while i < 50:
i += 1
VerificationCodeSystem.creat_code(d)
if (i % 10 == 0):
VerificationCodeSystem.prolong_length()
d += 1
else :
print(VerificationCodeSystem.get_codes(), "\n", VerificationCodeSystem.get_code_group(), VerificationCodeSystem.get_code_group("10"))
'''