This article mainly introduces the Python implementation to convert the number into Chinese, generally used for the amount of digital to Chinese capital, the Arabic numerals will be converted to uppercase Chinese, the need for friends can refer to the
At home on weekends, I wrote a small program to convert Arabic numerals to uppercase Chinese. The program did not undergo any optimization, haunt after detailed testing, hanging online, convenient for the future when there is a need to use directly.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80-81 |
#!/usr/bin/python #-*-encoding:utf-8-*- Import types class Notinteger Error (Exception): Pass class Outofrangeerror (Exception): Pass _mapping = (U ' 0 ', U ' one ', U ' two ', U ' three ', U ' four ', U ' V ') , U ' vi ', U ' seven ', U ' eight ', U ' Nine ',) _p0 = (U ', u ' x ', U ' hundred ', U ' thousand ',) _s4, _s8, _S16 = 4 * * * * * 8, _min = 0, 9 999999999999999 def _to_chinese4 (num): "Convert [0, 10000) between Arabic numerals ' assert (0 <= num and num < _S4) if Num < 10:return _mapping[num] Else:lst = [] While num >= 10:lst.append (num%) num = NUM/10 lst.append (num) c = len ( LST) # number result = U ' for IDX, Val in enumerate (LST): if Val!= 0:result + + _p0[idx] + _mapping[val] if idx < C-1 and Lst[idx + 1] = = U ' 0 ' return result[::-1].replace (U ' 10 ', U ' x ') 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 ' million ' Else:if low < _s4/10:return to4 (high) + U ' million zero ' + to4 (Low) Else:return to4 (high) + U ' million ' + to4 (Low) ; def _to_chinese16 (num): Assert (num < _s16) To8 = _to_chinese8 mod = _s8 high, low = num/mod, num% mod if low = = 0:r Eturn To8 (high) + U ' billion ' else:if low < _s8/10:return to8 (high) + U ' billion zero ' + to8 (Low) Else:return to8 (high) + U ' billion ' + To8 (Low) def to_chinese (num): If Type (num)!= types. Inttype and type (num)!= types. Longtype:raise notintegererror (U '%s is not an 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) |