python 隨機生成漢字


第一種方法:Unicode碼

在unicode碼中,漢字的范圍是(0x4E00, 9FBF)

這個方法比較簡單,但是有個小問題,unicode碼中收錄了2萬多個漢字,包含很多生僻的繁體字.

第二種方法:GBK2312

gbk2312對字符的編碼采用兩個字節相組合,第一個字節的范圍是0xB0-0xF7, 第二個字節的范圍是0xA1-0xFE.
對GBK2312編碼方式詳細的解釋請參看GBK2312編碼

GBK2312收錄了6千多常用漢字.兩種方法的取舍就看需求了.

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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM