第一種方法:Unicode碼
在unicode碼中,漢字的範圍是(0x4E00, 9FBF)
這個方法比較簡單,但是有個小問題,unicode碼中收錄了2萬多個漢字,包含很多生僻的繁體字.
第二種方法:GBK2312
gbk2312對字符的編碼採用兩個字節相組合,第一個字節的範圍是0xB0-0xF7, 第二個字節的範圍是0xA1-0xFE.
對GBK2312編碼方式詳細的解釋請參看GBK2312編碼
GBK2312收錄了6千多常用漢字.兩種方法的取捨就看需求了.
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ羣:531509025
尋找有志同道合的小夥伴,互幫互助,羣裏還有不錯的視頻學習教程和PDF電子書!
'''
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)