python:随机生成汉字//////英文字符

生成汉字:

第一种方法:Unicode码

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

1

2

3

4

5

import random

def Unicode():

 val = random.randint(0x4e00, 0x9fbf)

 return chr(val)

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

第二种方法:GBK2312

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

1

2

3

4

5

6

7

8

import random

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

GBK2312收录了6千多常用汉字

生成英文字母:

import random
s  = random.randint(65,90)
r=chr(s)
print(r)

猜你喜欢

转载自blog.csdn.net/ak739105231/article/details/83959865