数字转中文

发布在 编程
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
43
44
45
46
47
48
49
50
51
52
53
54
# coding: utf-8
"""\
规则:
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]))

注释和共享

  • 第 1 页 共 1 页
作者的图片

唐梓涯

Pythoner, Emacser, GNU/Linuxer
目前在微软技术支持掏粪


全栈工程师


中国无锡