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线程池的实现实例
Nov 18 Python
python常用web框架简单性能测试结果分享(包含django、flask、bottle、tornado)
Aug 25 Python
python虚拟环境virtualenv的使用教程
Oct 20 Python
Python入门之三角函数全解【收藏】
Nov 08 Python
Python使用pickle模块实现序列化功能示例
Jul 13 Python
OpenCV 轮廓检测的实现方法
Jul 03 Python
Django文件存储 自己定制存储系统解析
Aug 02 Python
Python遍历字典方式就实例详解
Dec 28 Python
Python通过4种方式实现进程数据通信
Mar 12 Python
Python根据指定文件生成XML的方法
Jun 29 Python
Pycharm安装第三方库失败解决方案
Nov 17 Python
正确的理解和使用Django信号(Signals)
Apr 14 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
一键删除顽固的空文件夹 软件下载
2007/01/26 PHP
snoopy PHP版的网络客户端提供本地下载
2008/04/15 PHP
探讨php中防止SQL注入最好的方法是什么
2013/06/10 PHP
浅谈使用 PHP 进行手机 APP 开发(API 接口开发)
2014/08/11 PHP
php学习笔记之面向对象
2014/11/08 PHP
php数组排序usort、uksort与sort函数用法
2014/11/17 PHP
php文件上传及下载附带显示文件及目录功能
2017/04/27 PHP
ThinkPHP 3使用OSS的方法
2018/07/19 PHP
JAVASCRIPT下判断IE与FF的比较简单的方式
2008/10/17 Javascript
js表格分页实现代码
2009/09/18 Javascript
jQuery中filter(),not(),split()使用方法
2010/07/06 Javascript
js change,propertychange,input事件小议
2011/12/20 Javascript
JS防止用户多次提交的简单代码
2013/08/01 Javascript
javascript字符串替换及字符串分割示例代码
2013/12/12 Javascript
基于javascript实现单选及多选的向右和向左移动实例
2015/07/25 Javascript
jquery获取复选框checkbox的值实现方法
2016/05/30 Javascript
详解AngularJs中$sce与$sceDelegate上下文转义服务
2016/09/21 Javascript
详解微信小程序实现WebSocket心跳重连
2018/07/31 Javascript
详解vue更改头像功能实现
2019/04/28 Javascript
VSCode使用之Vue工程配置eslint
2019/04/30 Javascript
微信小程序实现折线图的示例代码
2019/06/07 Javascript
Python实现二叉树结构与进行二叉树遍历的方法详解
2016/05/24 Python
Python实现二分查找与bisect模块详解
2017/01/13 Python
python opencv 二值化 计算白色像素点的实例
2019/07/03 Python
tensorflow 利用expand_dims和squeeze扩展和压缩tensor维度方式
2020/02/07 Python
JupyterNotebook 输出窗口的显示效果调整方法
2020/04/13 Python
Python调用OpenCV实现图像平滑代码实例
2020/06/19 Python
使用Keras预训练好的模型进行目标类别预测详解
2020/06/27 Python
HTML5 canvas基本绘图之绘制五角星
2016/06/27 HTML / CSS
英国独特礼物想法和个性化礼物网站:notonthehighstreet.com
2018/04/16 全球购物
军训自我鉴定
2013/12/14 职场文书
先进工作者个人总结
2015/02/15 职场文书
学校办公室主任岗位职责
2015/04/01 职场文书
红色经典电影观后感
2015/06/18 职场文书
vue项目支付功能代码详解
2022/02/18 Vue.js
Windows Server 2012 R2 磁盘分区教程
2022/04/29 Servers