python随机⽣成汉字的三种⽅法
第⼀种⽅法:Unicode码
在unicode码中,汉字的范围是(0x4E00, 9FBF)
这个⽅法⽐较简单,但是有个⼩问题,unicode码中收录了2万多个汉字,包含很多⽣僻的繁体字.
第⼆种⽅法:GBK2312
gbk2312对字符的编码采⽤两个字节相组合,第⼀个字节的范围是0xB0-0xF7, 第⼆个字节的范围是0xA1-0xFE.
GBK2312收录了6千多常⽤汉字.两种⽅法的取舍就看需求了.
random python
'''
Python⼤型免费公开课,适合初学者⼊门
加QQ:579817333 获取学习资料及必备软件。
'''
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)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。