python数字转对应中文的方法总结


Posted in Python onAugust 02, 2021

本文操作环境:

windows7系统,DELL G3电脑,python3.5版

python实现将阿拉伯数字转换成中文

第一种转换方式:

1  -->  一
    12   -->  一二
def num_to_char(num):
    """数字转中文"""
    num=str(num)
    new_str=""
    num_dict={"0":u"零","1":u"一","2":u"二","3":u"三","4":u"四","5":u"五","6":u"六","7":u"七","8":u"八","9":u"九"}
    listnum=list(num)
    # print(listnum)
    shu=[]
    for i in listnum:
        # print(num_dict[i])
        shu.append(num_dict[i])
    new_str="".join(shu)
    # print(new_str)
    return new_str

第二种转换方式:

1   -->   一
    12  -->   十二
    23  -->  二十三
_MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', u'十', u'十一', u'十二', u'十三', u'十四', u'十五', u'十六', u'十七',u'十八', u'十九')
_P0 = (u'', u'十', u'百', u'千',)
_S4 = 10 ** 4
def _to_chinese4(num):
    assert (0 <= num and num < _S4)
    if num < 20:
        return _MAPPING[num]
    else:
        lst = []
        while num >= 10:
            lst.append(num % 10)
            num = num / 10
        lst.append(num)
        c = len(lst)  # 位数
        result = u''
        for idx, val in enumerate(lst):
            val = int(val)
            if val != 0:
                result += _P0[idx] + _MAPPING[val]
                if idx < c - 1 and lst[idx + 1] == 0:
                    result += u'零'
        return result[::-1]

实例扩展:

#!/usr/bin/python
#-*- encoding: utf-8 -*-

import types

class NotIntegerError(Exception):
  pass

class OutOfRangeError(Exception):
  pass

_MAPPING = (u'零', u'一', u'二', u'三', u'四', u'五', u'六', u'七', u'八', u'九', )
_P0 = (u'', u'十', u'百', u'千', )
_S4, _S8, _S16 = 10 ** 4 , 10 ** 8, 10 ** 16
_MIN, _MAX = 0, 9999999999999999

def _to_chinese4(num):
  '''转换[0, 10000)之间的阿拉伯数字
  '''
  assert(0 <= num and num < _S4)
  if num < 10:
    return _MAPPING[num]
  else:
    lst = [ ]
    while num >= 10:
      lst.append(num % 10)
      num = num / 10
    lst.append(num)
    c = len(lst)  # 位数
    result = u''
    
    for idx, val in enumerate(lst):
      if val != 0:
        result += _P0[idx] + _MAPPING[val]
        if idx < c - 1 and lst[idx + 1] == 0:
          result += u'零'
    
    return result[::-1].replace(u'一十', u'十')
    
def _to_chinese8(num):
  assert(num < _S8)
  to4 = _to_chinese4
  if num < _S4:
    return to4(num)
  else:
    mod = _S4
    high, low = num / mod, num % mod
    if low == 0:
      return to4(high) + u'万'
    else:
      if low < _S4 / 10:
        return to4(high) + u'万零' + to4(low)
      else:
        return to4(high) + u'万' + to4(low)
      
def _to_chinese16(num):
  assert(num < _S16)
  to8 = _to_chinese8
  mod = _S8
  high, low = num / mod, num % mod
  if low == 0:
    return to8(high) + u'亿'
  else:
    if low < _S8 / 10:
      return to8(high) + u'亿零' + to8(low)
    else:
      return to8(high) + u'亿' + to8(low)
    
def to_chinese(num):
  if type(num) != types.IntType and type(num) != types.LongType:
    raise NotIntegerError(u'%s is not a integer.' % num)
  if num < _MIN or num > _MAX:
    raise OutOfRangeError(u'%d out of range[%d, %d)' % (num, _MIN, _MAX))
  
  if num < _S4:
    return _to_chinese4(num)
  elif num < _S8:
    return _to_chinese8(num)
  else:
    return _to_chinese16(num)
  
if __name__ == '__main__':
  print to_chinese(9000)

以上就是python数字转对应中文的方法总结的详细内容,更多关于python数字怎么转对应中文的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
初步认识Python中的列表与位运算符
Oct 12 Python
玩转python爬虫之URLError异常处理
Feb 17 Python
使用py2exe在Windows下将Python程序转为exe文件
Mar 04 Python
Python排序搜索基本算法之希尔排序实例分析
Dec 09 Python
python在文本开头插入一行的实例
May 02 Python
python通过tcp发送xml报文的方法
Dec 28 Python
对dataframe数据之间求补集的实例详解
Jan 30 Python
浅谈Python基础—判断和循环
Mar 22 Python
python3 动态模块导入与全局变量使用实例
Dec 22 Python
python 函数中的参数类型
Feb 11 Python
python中封包建立过程实例
Feb 18 Python
Python数据可视化之基于pyecharts实现的地理图表的绘制
Jun 10 Python
Python List remove()实例用法详解
Aug 02 #Python
Python中基础数据类型 set集合知识点总结
Aug 02 #Python
python unittest单元测试的步骤分析
Aug 02 #Python
python元组打包和解包过程详解
Aug 02 #Python
python字典进行运算原理及实例分享
Aug 02 #Python
Python中可变和不可变对象的深入讲解
Python基础数据类型tuple元组的概念与用法
Aug 02 #Python
You might like
phpfans留言版用到的数据操作类和分页类
2007/01/04 PHP
PHP 类商品秒杀计时实现代码
2010/05/05 PHP
PHP隐形一句话后门,和ThinkPHP框架加密码程序(base64_decode)
2011/11/02 PHP
ThinkPHP利用PHPMailer实现邮件发送实现代码
2013/09/26 PHP
浅谈PHP中JSON数据操作
2015/07/01 PHP
jquery批量设置属性readonly和disabled的方法
2014/01/24 Javascript
javascript/jquery获取地址栏url参数的方法
2014/03/05 Javascript
jQuery 中国省市两级联动选择附图
2014/05/14 Javascript
JavaScript 学习笔记之语句
2015/01/14 Javascript
JavaScript使用Replace进行字符串替换的方法
2015/04/14 Javascript
jquery+json实现分页效果
2016/03/07 Javascript
[原创]JS基于FileSaver.js插件实现文件保存功能示例
2016/12/08 Javascript
js基于myFocus实现轮播图效果
2017/02/14 Javascript
jQuery获取table下某一行某一列的值实现代码
2017/04/07 jQuery
Vue组件之全局组件与局部组件的使用详解
2017/10/09 Javascript
VUE Error: getaddrinfo ENOTFOUND localhost
2018/05/03 Javascript
vue 录制视频并压缩视频文件的方法
2018/07/27 Javascript
浅谈vux之x-input使用以及源码解读
2018/11/04 Javascript
TF-IDF与余弦相似性的应用(二) 找出相似文章
2017/12/21 Python
Python装饰器知识点补充
2018/05/28 Python
python 3.6.2 安装配置方法图文教程
2018/09/18 Python
python中将正则过滤的内容输出写入到文件中的实例
2018/10/21 Python
用Python PIL实现几个简单的图片特效
2019/01/18 Python
Python如何定义有可选参数的元类
2020/07/31 Python
python 操作excel表格的方法
2020/12/05 Python
荷兰领先的百货商店:De Bijenkorf
2018/10/17 全球购物
华硕新加坡官方网上商店:ASUS Singapore
2020/07/09 全球购物
武汉英思工程科技有限公司&ndash;ORACLE面试测试题目
2012/04/30 面试题
村官工作鉴定评语
2014/01/27 职场文书
应届大专生求职信
2014/06/26 职场文书
学习党的群众路线对照检查材料
2014/09/29 职场文书
群众路线教育实践活动学习笔记
2014/11/05 职场文书
2015公务员试用期工作总结
2014/12/12 职场文书
2015年世界环境日活动总结
2015/02/11 职场文书
技术员岗位职责范本
2015/04/11 职场文书
教师正风肃纪心得体会
2016/01/15 职场文书