第一种方法
在 unicode 码中, 汉字的范围是 (0x4E00, 9FBF)
- import random
- def Unicode():
- val = random.randint(0x4e00, 0x9fbf)
- return chr(val)
这个方法比较简单, 但是有个小问题, unicode 码中收录了 2 万多个汉字, 包含很多生僻的繁体字.
第二种方法
gbk2312 对字符的编码采用两个字节相组合, 第一个字节的范围是 0xB0-0xF7, 第二个字节的范围是 0xA1-0xFE.
值得注意的是, 对于第 55 区, D7FA-D7FE 的 5 个是没有编码的, 需要在两个字节组合的范围中特意剔除一下.
- 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 千多常用汉字, 两种方法的取舍就看需求了.
来源: http://www.bubuko.com/infodetail-3487934.html