將整數 (0 ~ 9999兆) 轉換為中文大寫數字 (壹貳參...),支援萬、億、兆單位,處理中間零、連續零、尾部零等邊界情況。常用於金額大寫轉換。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import types
_MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九')
_P0 = (u'', u'十', u'百', u'千')
_S4, _S8, _S16 = 10**4, 10**8, 10**16
_MIN, _MAX = 0, 9999999999999999
def _to_chinese4(num):
'''處理 [0, 10000) 區間'''
if num < 10: return _MAPPING[num]
lst = []
while num >= 10:
lst.append(num % 10)
num //= 10
lst.append(num)
result = u''
for idx, val in enumerate(lst):
if val != 0:
result += _P0[idx] + _MAPPING[val]
if idx < len(lst)-1 and lst[idx+1] == 0:
result += u'零'
return result[::-1].replace(u'一十', u'十')
def _to_chinese8(num):
if num < _S4: return _to_chinese4(num)
high, low = num // _S4, num % _S4
if low == 0: return _to_chinese4(high) + u'萬'
if low < _S4 // 10: return _to_chinese4(high) + u'萬零' + _to_chinese4(low)
return _to_chinese4(high) + u'萬' + _to_chinese4(low)
def _to_chinese16(num):
if num < _S8: return _to_chinese8(num)
high, low = num // _S8, num % _S8
if low == 0: return _to_chinese8(high) + u'億'
if low < _S8 // 10: return _to_chinese8(high) + u'億零' + _to_chinese8(low)
return _to_chinese8(high) + u'億' + _to_chinese8(low)
def to_chinese(num):
if not isinstance(num, (int, long)): raise TypeError('%s is not integer' % num)
if num < _MIN or num > _MAX: raise ValueError('out of range')
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) # 輸出: 九千