程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

A method of randomly generating Chinese characters in Python

編輯:Python

The operating environment is Python3.6 Next ,Python2 There are many solutions online .

The first method :Unicode code

stay unicode In code , The scope of Chinese characters is (0x4E00, 9FBF)

import random
def Unicode():
val = random.randint(0x4e00, 0x9fbf)
return chr(val)

This method is relatively simple , But there's a small problem ,unicode Code contains 2 More than ten thousand Chinese characters , It contains many rare traditional characters .

The second method :GBK2312

gbk2312 Two bytes are used to encode characters , The range of the first byte is 0xB0-0xF7, The range of the second byte is 0xA1-0xFE.
Yes GBK2312 For a detailed explanation of the encoding method, please refer to GBK2312 code

''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
import random
def GBK2312():
head = random.randint(0xb0, 0xf7)
body = random.randint(0xa1, 0xf9) # stay head Area code is 55 The last piece of 5 Chinese characters are garbled , In order to reduce the scope 
val = f'{
head:x}{
body:x}'
str = bytes.fromhex(val).decode('gb2312')
return str

GBK2312 Included 6 More than a thousand commonly used Chinese characters . The choice between the two methods depends on the demand .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved