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下singleton模式的实现方法
Jul 16 Python
Python标准库之多进程(multiprocessing包)介绍
Nov 25 Python
在Python中使用Mako模版库的简单教程
Apr 08 Python
在Python中操作文件之truncate()方法的使用教程
May 25 Python
Flask Web开发入门之文件上传(八)
Aug 17 Python
Python 数值区间处理_对interval 库的快速入门详解
Nov 16 Python
Python神奇的内置函数locals的实例讲解
Feb 22 Python
python程序控制NAO机器人行走
Apr 29 Python
Python实现投影法分割图像示例(一)
Jan 17 Python
django xadmin 管理器常用显示设置方式
Mar 11 Python
Python叠加矩形框图层2种方法及效果
Jun 18 Python
Keras在mnist上的CNN实践,并且自定义loss函数曲线图操作
May 25 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
《魔兽争霸3:重制版》翻车了?你想要的我们都没有
2019/11/07 魔兽争霸
PHP 和 MySQL 基础教程(三)
2006/10/09 PHP
PHP 加密解密内部算法
2010/04/22 PHP
php数组函数序列之array_search()- 按元素值返回键名
2011/11/04 PHP
LotusPhp笔记之:基于ObjectUtil组件的使用分析
2013/05/06 PHP
php常用Stream函数集介绍
2013/06/24 PHP
thinkphp3.2.2实现生成多张缩略图的方法
2014/12/19 PHP
如何实现php图片等比例缩放
2015/07/28 PHP
PHP-FPM和Nginx的通信机制详解
2019/02/01 PHP
用js实现的仿sohu博客更换页面风格(简单版)
2007/03/22 Javascript
jQuery html()等方法介绍
2009/11/18 Javascript
JavaScript 学习笔记(七)字符串的连接
2009/12/31 Javascript
js实现鼠标拖动图片并兼容IE/FF火狐/谷歌等主流浏览器
2013/06/06 Javascript
使用闭包对setTimeout进行简单封装避免出错
2013/07/10 Javascript
jQuery实现的感应鼠标悬停图片色彩渐显效果
2015/03/03 Javascript
Javascript中With语句用法实例
2015/05/14 Javascript
js代码实现随机颜色的小方块
2015/07/30 Javascript
Ajax实现不刷新取最新商品
2017/03/01 Javascript
关于foreach循环中遇到的问题小结
2017/05/08 Javascript
BootStrap中Table隐藏后显示问题的实现代码
2017/08/31 Javascript
从组件封装看Vue的作用域插槽的实现
2019/02/12 Javascript
vue实现PC端分辨率适配操作
2020/08/03 Javascript
Nodejs 微信小程序消息推送的实现
2021/01/20 NodeJs
Python中的ConfigParser模块使用详解
2015/05/04 Python
Python 学习教程之networkx
2019/04/15 Python
django settings.py 配置文件及介绍
2019/07/15 Python
使用K.function()调试keras操作
2020/06/17 Python
python中实现词云图的示例
2020/12/19 Python
使用CSS3设计地图上的雷达定位提示效果
2016/04/05 HTML / CSS
班级年度安全计划书
2014/05/01 职场文书
2016廉政教育学习心得体会
2016/01/25 职场文书
apache基于端口创建虚拟主机的示例
2021/04/22 Servers
python 定义函数 返回值只取其中一个的实现
2021/05/21 Python
Keras多线程机制与flask多线程冲突的解决方案
2021/05/28 Python
MySQL连接查询你真的学会了吗?
2021/06/02 MySQL
Python Matplotlib绘制等高线图与渐变色扇形图
2022/04/14 Python