運行環境在Python3.6下,Python2的解決方案網上有很多. ---2017.10.18
第一種方法:Unicode碼
在unicode碼中,漢字的范圍是(0x4E00, 9FBF)
import random
def Unicode():
val = random.randint(0x4e00, 0x9fbf)
return chr(val)
這個方法比較簡單,但是有個小問題,unicode碼中收錄了2萬多個漢字,包含很多生僻的繁體字.
第二種方法:GBK2312
gbk2312對字符的編碼采用兩個字節相組合,第一個字節的范圍是0xB0-0xF7, 第二個字節的范圍是0xA1-0xFE.
對GBK2312編碼方式詳細的解釋請參看GBK2312編碼
import random
def GBK2312():
head = random.randint(0xb0, 0xf7)
body = random.randint(0xa1, 0xf9) # 在head區號為55的那一塊最后5個漢字是亂碼,為了方便縮減下范圍
val = f'{head:x}{body:x}'
str = bytes.fromhex(val).decode('gb2312')
return str
GBK2312收錄了6千多常用漢字.兩種方法的取舍就看需求了.
另外推薦一篇對於deocde和encode的講解的博文