数字转汉字
2015-11-26 18:13
357 查看
def num2chinese(n): chinese = "" num_list = list("零一二三四五六七八九十") pos1 = list("十百千") pos2 = list("万亿兆") n_str = str(n) if len(n_str)>16: print("数字超出范围") return -1 str_list = [] while len(n_str)>0: str_list.insert(0, n_str[-4:]) n_str = n_str[:-4] zero_flag = False flag = False for cut_num in str_list: pos2 = pos2[:(len(str_list)-1)] if cut_num=="0000": zero_flag = True if pos2: pos2.pop() continue if zero_flag: chinese += "零" if 0<int(cut_num)<=10: if cut_num[0]=="0": chinese += "零" chinese += num_list[int(cut_num)] if pos2: chinese += pos2.pop() continue pos_1 = pos1[:(len(cut_num)-1)] for num in cut_num: if num=="0": flag = True if pos_1: pos_1.pop() continue if flag: chinese += "零" chinese += num_list[int(num)] if pos_1: chinese += pos_1.pop() if pos2: chinese += pos2.pop() if chinese[0:2]=="一十": chinese = chinese[1:] return chinese
第二种实现
def num2chinese(n):
danwei = list(" 十百千万十百千亿十百千兆十百千")
num_chinese = list("零一二三四五六七八九")
chinese=""
n2str = str(n)
length = len(n2str)
for i, v in enumerate(n2str):
chinese += num_chinese[int(v)] + danwei[length-i-1]
chinese = chinese[1:] if chinese[:2]=="一十" else chinese
zero_flag = False
new_chinese = ""
for x in chinese:
if x=="零" and not zero_flag:
zero_flag = True
new_chinese += "零"
continue
if x =="零" and zero_flag:
continue
if zero_flag and x in num_chinese:
zero_flag = False
if zero_flag and x in ("十", "百", "千"):
continue
if zero_flag and x in ("兆","亿","万"):
new_chinese = new_chinese[:-1]
zero_flag = False
new_chinese += x
new_chinese = new_chinese.replace("亿万","亿")
new_chinese = new_chinese.replace("兆亿","兆")
new_chinese = new_chinese.strip().strip("零")
return new_chinese
相关文章推荐
- 【C++】【STL】STL中部分数据结构的通俗化解释
- ios 7 模糊效果
- c# 可以有多个Main()函数
- mysql的主从复制配置
- IIS7启用gzip
- web.config中sessionState节点的配置方案
- Ubuntu建立和删除用户
- C和指针2.2
- 统计自然语言处理——n元语法(马尔可夫模型)小结
- dB是如何定义的,dBm与W之间的关系
- gcc常用命令
- Ubuntu中useradd和adduser的区别
- Html各组件MIME类型
- 用LINQ在集合中查询特定对象
- VI /vim 编辑器
- DirectX(7)着色方式
- 问题解决方法
- 链式基数排序
- ASP.NET多个提交按钮页面,回车Enter执行指定按钮的事件
- FJNU OJ 1035