阿拉伯数字转换成中文大写,中文货币的表达方式 python

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了阿拉伯数字转换成中文大写,中文货币的表达方式 python相关的知识,希望对你有一定的参考价值。

最近在qq群经常看到一个题目,网上查找资料发现,有人实现了一半内容,都是在处理0的问题上卡住了,自己就尝试用刚开始学习的python写了一下。python处理这个问题还是比较方便。

题目:

技术分享

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#转换
import re
chd = {‘ ‘:‘m‘,‘0‘:‘零‘,‘1‘:‘壹‘,‘2‘:‘贰‘,‘3‘:‘叁‘,‘4‘:‘肆‘,‘5‘:‘伍‘,‘6‘:‘陆‘,‘7‘:‘柒‘,‘8‘:‘捌‘,‘9‘:‘玖‘}
und = {‘S‘:‘拾‘,‘B‘:‘佰‘,‘Q‘:‘仟‘,‘W‘:‘万‘,‘Y‘:‘亿‘}

#判断输入内容(首位不为零的整数)
ips = raw_input(‘Please input a number: ‘)
while ips[0] == ‘0‘:
    ips = raw_input(‘Wrong,the first non-zero: ‘)
else:
    while ips.isdigit():
        break
    else:
        ips = raw_input(‘Wrong,please input a number: ‘)
if len(ips) <= 9:
    #输出9位字符,右对齐,补空格
    ips = ips.rjust(9) 
    #转换成大写
    ops = chd[ips[0]]+und[‘Y‘]+chd[ips[1]]+und[‘Q‘]+chd[ips[2]]+und[‘B‘]+chd[ips[3]]+und[‘S‘]+chd[ips[4]]+und[‘W‘]+chd[ips[5]]+und[‘Q‘]+chd[ips[6]]+und[‘B‘]+chd[ips[7]]+und[‘S‘]+chd[ips[8]]+‘元‘
    #无用的数字位替换为空
    ops = re.sub(‘(m...)+‘,‘‘,ops)
    #处理零
    ops = re.sub(‘零元$‘,‘元‘,ops)
    ops = re.sub(‘零万‘,‘万‘,ops)
    ops = re.sub(‘(零...)+‘,‘零‘,ops)
    ops = re.sub(‘零万‘,‘万‘,ops)
    ops = re.sub(‘零元$‘,‘元‘,ops)
    print ops
else:
    print ‘The number is too big.‘

测试发现正则部分不全面,修改如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#转换
import re
chd = {‘ ‘:‘m‘,‘0‘:‘零‘,‘1‘:‘壹‘,‘2‘:‘贰‘,‘3‘:‘叁‘,‘4‘:‘肆‘,‘5‘:‘伍‘,‘6‘:‘陆‘,‘7‘:‘柒‘,‘8‘:‘捌‘,‘9‘:‘玖‘}
und = {‘S‘:‘拾‘,‘B‘:‘佰‘,‘Q‘:‘仟‘,‘W‘:‘万‘,‘Y‘:‘亿‘}

#判断输入内容(首位不为零的整数)
ips = raw_input(‘Please input a number: ‘)
while ips[0] == ‘0‘:
    ips = raw_input(‘Wrong,the first non-zero: ‘)
else:
    while ips.isdigit():
        break
    else:
        ips = raw_input(‘Wrong,please input a number: ‘)
if len(ips) <= 9:
    #输出9位字符,右对齐,补空格
    ips = ips.rjust(9) 
    #转换成大写
    ops = chd[ips[0]]+und[‘Y‘]+chd[ips[1]]+und[‘Q‘]+chd[ips[2]]+und[‘B‘]+chd[ips[3]]+und[‘S‘]+chd[ips[4]]+und[‘W‘]+chd[ips[5]]+und[‘Q‘]+chd[ips[6]]+und[‘B‘]+chd[ips[7]]+und[‘S‘]+chd[ips[8]]+‘元‘
    #无用的数字位替换为空
    ops = re.sub(‘(m...)+‘,‘‘,ops)
    #处理零
    ops = re.sub(‘零元$‘,‘元‘,ops)
    ops = re.sub(‘零万‘,‘万‘,ops)
    ops = re.sub(‘(零...)+‘,‘零‘,ops)
    ops = re.sub(‘亿零万‘,‘亿零‘,ops)
    ops = re.sub(‘零万‘,‘万‘,ops)
    ops = re.sub(‘零元$‘,‘元‘,ops)
    ops = re.sub(‘亿零元$‘,‘亿元‘,ops)
    print ops
else:
    print ‘The number is too big.‘



本文出自 “大碗儿板儿面” 博客,请务必保留此出处http://banmian.blog.51cto.com/10975819/1747441

以上是关于阿拉伯数字转换成中文大写,中文货币的表达方式 python的主要内容,如果未能解决你的问题,请参考以下文章

7-1 货币转换

请问在Excel里怎么用VBA把中文大写的数字转换成阿拉伯数字?

js怎么把数字金额转换成中文大写金额

PHP 数字金额转换成中文大写金额的函数 数字转中文

如何自动把数字转换成大写的金钱?

小写数字自动转换成大写人民币金额两张表怎么在桌面找不同吗?