"""\ 规则: 1. 中文分为数字(零、一、二、三、四、伍、六、七、八、九),数位[个、十、百、千、万、亿]和符号[负,点]三部分 2. 数位个略去 3. 以一十开头略去首位一 4. 数位为零,保留数字零略去该数位单位 5. 连续数位为零,保留一个零 6. 个,万,亿位为零,略去零 7. """ numbers = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"] units = ["亿", "万", "千", "百", "十", ""] def i2c(i, recursive=False): if i < 0: return '负'+i2c(abs(i)) if i == 0: return "零" elif i < pow(10, 4): result = "" for d, u in zip(str(i).zfill(4), units[2:]): result += numbers[int(d)]+u if d != "0" else "零" elif i < pow(10, 8): wj, rest = divmod(i, pow(10, 4)) result = i2c(wj)+"万"+("零" if rest < pow(10, 3) else "")+i2c(rest, True) else: yi, rest = divmod(i, pow(10, 8)) result = i2c(yi)+"亿"+("零" if rest < pow(10, 7) else "")+i2c(rest, True) result = "零".join(result.replace("零", " ").split()) return result[1:] if result.startswith('一十') and not recursive else result def f2c(f): if f == '': f = '0' return '点'+''.join(map(lambda d: numbers[int(d)], f)) def n2c(n): nsplit = n.split('.') i = int(nsplit[0]) if nsplit[0] else 0 if len(nsplit) == 1: return i2c(i) elif len(nsplit) == 2 and n != '.': return i2c(i)+f2c(nsplit[1]) else: raise ValueError if __name__ == '__main__': import sys print(n2c(sys.argv[1]))
|