Python 随机生成中文验证码(转载)



转自:点击打开链接

# -*- coding: utf-8 -*-
import Image,ImageDraw,ImageFont
import random
import math, string  

class RandomChar():
  """用于随机生成汉字"""
  @staticmethod
  def Unicode():
    val = random.randint(0x4E00, 0x9FBF)
    return unichr(val)  

  @staticmethod
  def GB2312():
    head = random.randint(0xB0, 0xCF)
    body = random.randint(0xA, 0xF)
    tail = random.randint(0, 0xF)
    val = ( head << 8 ) | (body << 4) | tail
    str = "%x" % val
    return str.decode('hex').decode('gb2312')  

class ImageChar():
  def __init__(self, fontColor = (0, 0, 0),
                     size = (100, 40),
                     fontPath = 'wqy.ttc',
                     bgColor = (255, 255, 255),
                     fontSize = 20):
    self.size = size
    self.fontPath = fontPath
    self.bgColor = bgColor
    self.fontSize = fontSize
    self.fontColor = fontColor
    self.font = ImageFont.truetype(self.fontPath, self.fontSize)
    self.image = Image.new('RGB', size, bgColor)  

  def rotate(self):
    self.image.rotate(random.randint(0, 30), expand=0)  

  def drawText(self, pos, txt, fill):
    draw = ImageDraw.Draw(self.image)
    draw.text(pos, txt, font=self.font, fill=fill)
    del draw  

  def randRGB(self):
    return (random.randint(0, 255),
           random.randint(0, 255),
           random.randint(0, 255))  

  def randPoint(self):
    (width, height) = self.size
    return (random.randint(0, width), random.randint(0, height))  

  def randLine(self, num):
    draw = ImageDraw.Draw(self.image)
    for i in range(0, num):
      draw.line([self.randPoint(), self.randPoint()], self.randRGB())
    del draw  

  def randChinese(self, num):
    gap = 5
    start = 0
    for i in range(0, num):
      char = RandomChar().GB2312()
      x = start + self.fontSize * i + random.randint(0, gap) + gap * i
      self.drawText((x, random.randint(-5, 5)), RandomChar().GB2312(), self.randRGB())
      self.rotate()
    self.randLine(18)  

  def save(self, path):
    self.image.save(path)


要使用Python随机生成验证码,可以使用以下几种方法: 方法一:使用range()函数和random.sample()函数生成验证码 首先,引入random库。然后,编写一个函数来生成指定位数的验证码。在函数中,使用range()函数来生成数字、大写字母和小写字母的列表。然后,使用random.sample()函数从列表中随机抽取指定数量的元素。最后,将抽取到的元素拼接成一个字符串,并将其作为函数的返回值。可以调用这个函数来生成6位验证码。 代码示例: import random def generate_code(length): code_list = [] for i in range(10): code_list.append(str(i)) # 生成数字 for i in range(65, 91): code_list.append(chr(i)) # 生成大写字母 for i in range(97, 123): code_list.append(chr(i)) # 生成小写字母 random_code = random.sample(code_list, length) code = ''.join(random_code) return code if __name__ == '__main__': code = generate_code(6) print(code) 方法二:使用random.randint()函数生成验证码 同样,需要引入random库。然后,使用for循环和random.randint()函数生成随机数字、大写字母和小写字母。通过chr()函数将ASCLL值转换为字符,并将其拼接成一个字符串。最后,将字符串打印出来。 代码示例: import random code = '' for i in range(6): n = random.randint(0, 9) # 随机生成数字 b = chr(random.randint(65, 90)) # 随机生成大写字母 s = chr(random.randint(97, 122)) # 随机生成小写字母 code += str(random.choice([n, b, s])) print(code) 以上两种方法都可以用来随机生成一组6位验证码,每个字符可以是数字、大写字母或小写字母。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python生成验证码【两种方法】](https://blog.csdn.net/qq_46556714/article/details/121174569)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值