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 使用os.remove删除文件夹时报错的解决方法
Jan 13 Python
Python栈算法的实现与简单应用示例
Nov 01 Python
python如何读写csv数据
Mar 21 Python
Python 统计字数的思路详解
May 08 Python
Python使用re模块正则提取字符串中括号内的内容示例
Jun 01 Python
win7+Python3.5下scrapy的安装方法
Jul 31 Python
python将一个英文语句以单词为单位逆序排放的方法
Dec 20 Python
python中调试或排错的五种方法示例
Sep 12 Python
Pytorch实现各种2d卷积示例
Dec 30 Python
Python自定义sorted排序实现方法详解
Sep 18 Python
python3字符串输出常见面试题总结
Dec 01 Python
用Python监控你的朋友都在浏览哪些网站?
May 27 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
解决163/sohu/sina不能够收到PHP MAIL函数发出邮件的问题
2009/03/13 PHP
php记录日志的实现代码
2011/08/08 PHP
深入PHP中慎用双等于(==)的详解
2013/06/06 PHP
PHP内存缓存Memcached类实例
2014/12/08 PHP
验证token、回复图文\文本、推送消息的实用微信类php代码
2016/06/28 PHP
PHP文件及文件夹操作之创建、删除、移动、复制
2016/07/13 PHP
Laravel框架分页实现方法分析
2018/06/12 PHP
实例介绍PHP删除数组中的重复元素
2019/03/03 PHP
Javascript中的数学函数集合
2007/05/08 Javascript
兼容FF和IE的动态table示例自写
2013/10/21 Javascript
JS实现很实用的对联广告代码(可自适应高度)
2015/09/18 Javascript
浅析JavaScript Array和string的转换(推荐)
2016/05/20 Javascript
jQuery实现点击后高亮背景固定显示的菜单效果【附demo源码下载】
2016/09/21 Javascript
JavaScript中数组Array方法详解
2017/02/27 Javascript
JavaScript运动框架 解决速度正负取整问题(一)
2017/05/17 Javascript
Angularjs 实现动态添加控件功能
2017/05/25 Javascript
jQuery实现拼图小游戏(实例讲解)
2017/07/24 jQuery
使用Vue动态生成form表单的实例代码
2018/04/26 Javascript
详解angular路由高亮之RouterLinkActive
2018/04/28 Javascript
JS开发常用工具函数(小结)
2019/07/04 Javascript
关于Vue中axios的封装实例详解
2019/10/20 Javascript
JavaScript交换变量的常用方法小结【4种方法】
2020/05/07 Javascript
Python黑帽编程 3.4 跨越VLAN详解
2016/09/28 Python
TensorFlow搭建神经网络最佳实践
2018/03/09 Python
Pycharm自带Git实现版本管理的方法步骤
2020/09/18 Python
python使用smtplib模块发送邮件
2020/12/17 Python
python语言time库和datetime库基本使用详解
2020/12/25 Python
scrapy实践之翻页爬取的实现
2021/01/05 Python
普师专业个人自荐信范文
2013/11/26 职场文书
管理部副部长岗位职责范文
2014/03/09 职场文书
何时使用Map来代替普通的JS对象
2021/04/29 Javascript
Python爬取英雄联盟MSI直播间弹幕并生成词云图
2021/06/01 Python
python图片灰度化处理的几种方法
2021/06/23 Python
python中Matplotlib绘制直线的实例代码
2021/07/04 Python
浅谈Redis的事件驱动模型
2022/05/30 Redis
hive数据仓库新增字段方法
2022/06/25 数据库