python--随机生成汉字、数字

一、随机生成汉字:

第一种方法:Unicode码

在unicode码中,汉字的范围是(0x4E00, 9FBF)

这个方法比较简单,但是有个小问题,unicode码中收录了2万多个汉字,包含很多生僻的繁体字.

第二种方法:GBK2312

gbk2312对字符的编码采用两个字节相组合,第一个字节的范围是0xB0-0xF7, 第二个字节的范围是0xA1-0xFE.
对GBK2312编码方式详细的解释请参看GBK2312编码

GBK2312收录了6千多常用汉字.两种方法的取舍就看需求了.

import random

def Unicode():
    val = random.randint(0x4e00, 0x9fbf)
    return chr(val)

def GBK2312():
    head = random.randint(0xb0, 0xf7)
    body = random.randint(0xa1, 0xfe)
    val = f'{head:x} {body:x}'
    str = bytes.fromhex(val).decode('gb2312')
    return str

if __name__ == '__main__':
    print(Unicode())
    print(GBK2312())

第三种方法:列表读取

# encoding: utf-8
import random

first_name = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "上官", "", ""]
second_name = ["", "", "建国", "", "", "万里", "爱民", "", "", "", "", "", "", "", "志宏", "", "", "", "","明浩", "", "", "", ""]
name = random.choice(first_name) + random.choice(second_name)

print(name)

二、随机生成数字:

phone_f = "182"
phone_e = random.randint(10000000,99999999)
phone = phone_f + str(phone_e)

三、其他随机语句:

import random
import string

print(random.random())#随机浮点数,默认取0-1,不能指定范围
print(random.randint(1,20))#随机整数
print(random.randrange(1,20))#随机产生一个range
print(random.choice('x23serw4'))#随机取一个元素
print(random.sample('hello',2))#从序列中随机取几个元素
print(random.uniform(1,9))#随机取浮点数,可以指定范围
x = [1,2,3,4,6,7]
random.shuffle(x)#洗牌,打乱顺序,会改变原list的值
print(x)
print(string.digits)#所有的数字
print(string.ascii_letters)#所有的字母
print(string.punctuation)#所有的特殊字符

原文地址:https://www.cnblogs.com/yitao326/p/11319896.html