数字转中文

数字转中文

最近公司小哥哥出了个面试题,需求是将一个中文表示的数字,转成中文写法。大家都给出了自己的解法,挺有趣的。

解法

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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python
# coding: utf-8

def num2cn(num):
num = int(num)
if num == 0:
return '零'
elif num == 1:
return '一'
elif num == 2:
return '二'
elif num == 3:
return '三'
elif num == 4:
return '四'
elif num == 5:
return '五'
elif num == 6:
return '六'
elif num == 7:
return '七'
elif num == 8:
return '八'
elif num == 9:
return '九'
else:
print('input type error')
exit(1)

suffix = ['','十','百','千','万','十万','百万','千万','亿','十亿','百亿','千亿']

# # 1. 定义个到千的规则

import re
import random

def one2thousand(x):
first_no_zero = False
# 保存结果
result = []
x = str(x)
# 填充到千位
x = x.rjust(4,"0")
len_x = len(x)
sub_suffix = suffix[:len_x]
sub_suffix.reverse()

for index, num in enumerate(x):
if num == '0':
if first_no_zero == True:
# 在遇到首个非零数字前,遇到的0都是填充的
result.append(num2cn(num))
else:
result.append(num2cn(num))
result.append(sub_suffix[index])
first_no_zero = True
if len(result) == 0:
# 输入为0的特殊情况
return '零'

out = "".join(result)
# 处理中间的零,将多个“零”,变为一个“零”,如一千零零一 --> 一千零一
out = re.sub('零+','零',out)
# 处理末尾的零,,如一千一百零 --> 一千一百
out = re.sub('零+$','',out)
return out

for i in range(10):
inp = str(random.randint(0,10000))
print('数字:%s \t中文读法:%s'%(inp,one2thousand(inp)))


# # 2. 个到千的规则定义好了,接着将一个数字拆分为许多个到千来处理



suffix2 = ['亿','万','']

def zh_cnNum(x):
result = []
x = str(x)
len_x = len(x)
# 将x填充到千亿位
x = x.rjust(len(suffix),"0")
sub_suffix = suffix[:4]
# 每次取出4位进行千位读法,并加上单位,如'亿','万',...
for i in range(3):
sub_x = x[i*4:i*4+4]
out = one2thousand(sub_x)
if out != '零':
result.append(out)
result.append(suffix2[i])

if len(result) == 0:
# 输入为0的特殊情况
return '零'

return "".join(result)

for i in range(10):
inp = str(random.randint(0,100000000001))
print('数字:%s \t中文读法:%s'%(inp,zh_cnNum(inp)))