python 中文汉字钱转成阿拉伯数字钱

xiaoxiao2021-02-27  199

自己写的一个中文汉字钱转成阿拉伯数字钱的python demo.

例如:

         二千万零二十三块              ==>     20000023

       三百二十万五百两十三元    ==>     3200523

注: 最大金额九亿九千九百....九十九块

更完整更全的功能,包括汉字和数字混合,支持毛,角,分等. 请移步 https://github.com/chenzhi1992/chinese2num

代码:

# 记录个、十、百、...亿每一位的数字,一共9位 num_money = [] # 钱中数量单位 mon = ['十', '百', '千', '万', '亿'] def func(m_str): ''' 函数作用:判断m_str中有没有数字,并将数字存入num_money中。没有数字,存0 :param m_str: 输入汉字钱的字符串,并存入列表中 :return: 无 ''' money = 0 if '一' in m_str: money = 1 elif '二' in m_str or '两' in m_str: money = 2 elif '三' in m_str: money = 3 elif '四' in m_str: money = 4 elif '五' in m_str: money = 5 elif '六' in m_str: money = 6 elif '七' in m_str: money = 7 elif '八' in m_str: money = 8 elif '九' in m_str: money = 9 else: money = 0 # print(str(money)) num_money.append(money) def fun2(num, m_str): ''' 函数作用:将m_str以'亿,万,千,百,十'为分割区间分成左右两个部分 :param num: 类型int,用于提取mon[num]中的值,即提取钱的某一个数量单位 :param m_str: 输入汉字钱的字符串,并存入列表中 :return: 返回m_str被分成的俩个值 例子:fun2(2,['五','千','五','百']) 返回:['五'],['五','百'] ''' a = mon[num] ind = m_str.index(a) m_left = m_str[:ind] m_right = m_str[ind + 1 :] return m_left, m_right def fact(a, m_str): if a < 0 : func(m_str) else: if mon[a] in m_str: m_left, m_right = fun2(a, m_str) if mon[a] == '万': fact(2, m_left) else: func(m_left) fact(a - 1, m_right) else: if a == 3: num_money.append(0) num_money.append(0) num_money.append(0) num_money.append(0) else: m_left = '-1' func(m_left) fact(a - 1, m_str) def num2money(liststr): _money = 0 for ind, num in enumerate(liststr): m = num * pow(10, 8 - ind) _money += m return _money num = 4 m_str = '我要取二亿二万零二百二十两块' liststr = list(m_str) fact(num, liststr) money = num2money(num_money) print(money) # print(num_money)

转载请注明原文地址: https://www.6miu.com/read-10361.html

最新回复(0)