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 17 Python
简单的编程0基础下Python入门指引
Apr 01 Python
Python中使用Queue和Condition进行线程同步的方法
Jan 19 Python
python 爬取微信文章
Jan 30 Python
Python实现ssh批量登录并执行命令
Oct 25 Python
一个基于flask的web应用诞生 用户注册功能开发(5)
Apr 11 Python
python使用Plotly绘图工具绘制柱状图
Apr 01 Python
详解python 爬取12306验证码
May 10 Python
JupyterNotebook 输出窗口的显示效果调整实现
Sep 22 Python
Python self用法详解
Nov 28 Python
Python os和os.path模块详情
Apr 02 Python
python Tkinter模块使用方法详解
Apr 07 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
php去除字符串换行符示例分享
2014/02/13 PHP
phpMyAdmin自动登录和取消自动登录的配置方法
2014/05/12 PHP
PHP多文件上传类实例
2015/03/07 PHP
php实现在服务器端调整图片大小的方法
2015/06/16 PHP
php设置页面超时时间解决方法
2015/09/22 PHP
php实现微信扫码自动登陆与注册功能
2016/09/22 PHP
在一个浏览器里呈现所有浏览器测试结果的前端测试工具的思路
2010/03/02 Javascript
passwordStrength 基于jquery的密码强度检测代码使用介绍
2011/10/08 Javascript
利用NodeJS的子进程(child_process)调用系统命令的方法分享
2013/06/05 NodeJs
jQuery-ui引入后Vs2008的无智能提示问题解决方法
2014/02/10 Javascript
手机开发必备技巧:javascript及CSS功能代码分享
2015/05/25 Javascript
JQuery操作textarea,input,select,checkbox方法
2015/09/02 Javascript
详解Backbone.js框架中的模型Model与其集合collection
2016/05/05 Javascript
自动化测试读写64位操作系统的注册表
2016/08/15 Javascript
原生js实现下拉框功能(支持键盘事件)
2017/01/13 Javascript
javascript深拷贝的原理与实现方法分析
2017/04/10 Javascript
JS奇技之利用scroll来监听resize详解
2017/06/15 Javascript
利用javascript如何随机生成一定位数的密码
2017/09/22 Javascript
vuejs使用axios异步访问时用get和post的实例讲解
2018/08/09 Javascript
Element InfiniteScroll无限滚动的具体使用方法
2020/07/27 Javascript
微信小程序组件生命周期的踩坑记录
2021/03/03 Javascript
[12:51]71泪洒现场!是DOTA2让经典重现
2014/03/24 DOTA
python3使用urllib模块制作网络爬虫
2016/04/08 Python
python中解析json格式文件的方法示例
2017/05/03 Python
Python自定义函数实现求两个数最大公约数、最小公倍数示例
2018/05/21 Python
python中join()方法介绍
2018/10/11 Python
Python中面向对象你应该知道的一下知识
2019/07/10 Python
详解Django CAS 解决方案
2019/10/30 Python
在Windows上安装和配置 Jupyter Lab 作为桌面级应用程序教程
2020/04/22 Python
介绍一下如何利用路径遍历进行攻击及如何防范
2014/01/19 面试题
个人简历自我评价八例
2013/10/31 职场文书
一体化教学实施方案
2014/05/10 职场文书
农民工工资保障承诺书
2015/05/04 职场文书
初一年级组工作总结
2015/08/12 职场文书
2019企业文化管理制度范本!
2019/08/06 职场文书
golang中的空slice案例
2021/04/27 Golang