This article mainly introduces how to convert numbers into Chinese characters in Python. it is generally used to convert numbers into Chinese capital, that is, to convert Arabic numerals into Chinese capital. if you need a friend, you can refer to at home next weekend, I wrote a small program to convert Arabic numerals into uppercase Chinese. The program has not been optimized, and has gone through detailed tests. it is mounted to the Internet for use directly when necessary in the future.
#! /Usr/bin/python #-*-encoding: UTF-8-*-import typesclass NotIntegerError (Exception): passclass OutOfRangeError (Exception): pass_MAPPING = (u '0 ', u'1', u'2', u'3', u'4', u'5', u'6', u'7', u'8 ', u'9',) _ P0 = (u'', u'10', u'bai', u'qi',) _ S4, _ S8, _ S16 = 10 ** 4, 10 ** 8, 10 ** 16_MIN, _ MAX = 0, 999999999999999999def _ to_chinese4 (num): ''' conversion [0, 10000) between the Arabic numerals '''assert (0 <= num and num <_ S4) if num <10: Return _ MAPPING [num] else: lst = [] while num> = 10: lst. append (num % 10) num = num/10 lst. append (num) c = len (lst) # Number of digits result = u'' for idx, val in enumerate (lst): if val! = 0: result + = _ P0 [idx] + _ MAPPING [val] if idx <c-1 and lst [idx + 1] = 0: result + = u'0' return result [:-1]. replace (u '10 ', u '10') def _ to_chinese8 (num): assert (num <_ S8) to4 = _ to_chinese4 if num <_ S4: return to4 (num) else: mod = _ S4 high, low = num/mod, num % mod if low = 0: return to4 (high) + u'wan' else: if low <_ S4/10: return to4 (high) + u 'Ten Thousand 0' + to4 (low) else: return to4 (high) + u 'Ten Thousand' + To4 (low) def _ to_chinese16 (num): assert (num <_ S16) to8 = _ to_chinese8 mod = _ S8 high, low = num/mod, num % mod if low = 0: return to8 (high) + u 'yie' else: if low <_ S8/10: return to8 (high) + u 'yi0' + to8 (low) else: return to8 (high) + u 'yie' + to8 (low) def to_chinese (num): if type (num )! = Types. IntType and type (num )! = Types. longType: raise NotIntegerError (u '% s is not a integer. '% num) if num <_ MIN or num> _ MAX: raise OutOfRangeError (u' % d out of range [% d, % d)' % (num, _ MIN, _ MAX) if num <_ S4: return _ to_chinese4 (num) elif num <_ S8: return _ to_chinese8 (num) else: return _ to_chinese16 (num) if _ name _ = '_ main _': print to_chinese (9000)