#! /Usr/bin/python #-*-Encoding: UTF-8 -*- Import types Class NotIntegerError (Exception ): Pass Class 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'100', u'kil ',) _ S4, _ S8, _ S16 = 10 ** 4, 10 ** 8, 10 ** 16 _ MIN, _ MAX = 0, 9999999999999999 Def _ to_chinese4 (num ): ''' Converts Arabic numerals between 0 and 10000. ''' 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) # 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'110', 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'wan' + 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'100' Else: If low <_ S8/10: Return to8 (high) + u 'yi0' + to8 (low) Else: Return to8 (high) + u'100 '+ 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) |