Last active
August 29, 2015 14:19
-
-
Save axiaoxin/be10d8a8493082d449bd to your computer and use it in GitHub Desktop.
rand_cn_char.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #-*- coding:utf-8 -*- | |
| __author__ = 'ashin' | |
| import random | |
| def rand_cn_char(length=1, encode="gb2312"): | |
| '''get the random chinese characters''' | |
| chars = [] | |
| try: | |
| if encode=="gb2312": | |
| for i in xrange(length): | |
| head = random.randint(0xB0, 0xCF) | |
| body = random.randint(0xA, 0xF) | |
| tail = random.randint(0, 0xF) | |
| val = ( head << 8 ) | (body << 4) | tail | |
| char = "%x" % val | |
| chars.append(char.decode('hex').decode('gb2312')) | |
| elif encode == "unicode": | |
| for i in xrange(length): | |
| val = random.randint(0x4E00, 0x9FBF) | |
| chars.append(unichr(val)) | |
| except: | |
| chars.append(u'亏') | |
| return ''.join(chars) | |
| if __name__ == "__main__": | |
| chars = rand_cn_char() | |
| print chars |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment