Python實現(xiàn)中文大寫金額轉阿拉伯數(shù)字
在財務票據(jù)中,中文大寫金額(如“貳拾捌萬壹仟柒佰伍拾伍元壹角玖分”)被廣泛使用以防止篡改。但在數(shù)據(jù)處理時,我們需要將其轉換為阿拉伯數(shù)字形式。本文將帶你一步步解析如何用Python實現(xiàn)這一轉換。
一、核心思路拆解
整個轉換過程可分為三步:
- 中文數(shù)字解析 :將“貳拾捌”等字符串轉換為數(shù)字
- 單位分割 :處理“億”、“萬”等大單位分隔
- 元角分處理 :分離并轉換金額中的整數(shù)與小數(shù)部分
二、中文數(shù)字解析實現(xiàn)
def chinese_to_number(chinese_str):
result = 0
temp = 0
unit = 1
for char in chinese_str:
if char in chinese_to_arabic:
temp += chinese_to_arabic[char] * unit
if unit < 10:
unit = 1 # 重置單位為個位
elif char in unit_map:
unit = unit_map[char]
temp = 1 if temp == 0 else temp # 處理"拾"等單位前無數(shù)字的情況
result += temp * unit
temp = 0
unit = 1
return result + temp解析邏輯 :
- 遍歷每個字符,遇到數(shù)字字符(壹、貳等)時累加到臨時變量
- 遇到單位字符(拾、佰等)時,將當前累加值乘以單位后加入結果
- 特殊處理連續(xù)單位(如"拾萬"自動補1)
三、大單位分割策略
def extract_parts_yi_wan(s):
result = {"億": "", "萬": "", "一": ""}
if "億" in s:
yi_index = s.index("億")
result["億"] = s[:yi_index]
after_yi = s[yi_index+1:]
if "萬" in after_yi:
wan_index = after_yi.index("萬")
result["萬"] = after_yi[:wan_index]
result["一"] = after_yi[wan_index+1:]
else:
result["一"] = after_yi
elif "萬" in s:
wan_index = s.index("萬")
result["萬"] = s[:wan_index]
result["一"] = s[wan_index+1:]
else:
result["一"] = s
return result分割規(guī)則 :
- 優(yōu)先分割"億"級單位
- 在億級后的部分繼續(xù)分割"萬"級
- 剩余部分作為個位部分處理
例如:"貳億叁仟萬肆仟伍佰"會被分割為:
億:"貳"
萬:"叁仟"
一:"肆仟伍佰"
四、元角分綜合處理
def convert_amounts(amount_list):
pattern = re.compile(
r'([零壹貳叁肆伍陸柒捌玖拾佰仟萬億]+)元?'
r'((?:零|[壹貳叁肆伍陸柒捌玖]+)角)?'
r'((?:零|[壹貳叁肆伍陸柒捌玖]+)分)?'
)
converted = []
for amount in amount_list:
match = pattern.findall(amount)
if not match:
converted.append("無法轉換")
continue
yuan, jiao, fen = match[0]
parts = extract_parts_yi_wan(yuan)
total = 0
# 處理億、萬、個位部分
for unit, value in parts.items():
if not value:
continue
num = chinese_to_number(value)
if unit == "億":
num *= 100000000
elif unit == "萬":
num *= 10000
total += num
# 處理角分
if jiao and jiao != '零角':
total += chinese_to_arabic[jiao[:-1]] * 0.1
if fen and fen != '零分':
total += chinese_to_arabic[fen[:-1]] * 0.01
converted.append(f"{total:.2f}")
return converted處理流程 :
- 正則提取元、角、分三部分
- 分別解析各部分數(shù)值
- 按單位權重累加計算總金額
- 保留兩位小數(shù)輸出
五、測試驗證
amounts = [
'貳拾捌萬壹仟柒佰伍拾伍元壹角玖分',
'貳拾伍萬捌仟肆佰玖拾壹元'
]
print(convert_amounts(amounts)) 輸出結果:
['281755.19', '258491.00']
六、全部代碼
import re
# 定義中文數(shù)字到阿拉伯數(shù)字的映射
chinese_to_arabic = {
'零': 0, '壹': 1, '貳': 2, '叁': 3, '肆': 4,
'伍': 5, '陸': 6, '柒': 7, '捌': 8, '玖': 9,
}
unit_map = {'拾': 10, '佰': 100, '仟': 1000}
def chinese_to_number(chinese_str):
result = 0
temp_result = 0
unit = 1
for char in chinese_str:
if char in chinese_to_arabic:
temp_result += chinese_to_arabic[char] * unit
if unit < 10: # 當前處理的是個位數(shù),需要重置unit
unit = 1
elif char in unit_map:
unit = unit_map[char]
temp_result = 1 if temp_result == 0 else temp_result
result += temp_result * unit
temp_result = 0
unit = 1
elif char in ['元', '角', '分']:
break
result += temp_result
return result
def extract_parts_yi_wan(s):
# 初始化結果字典
result = {"億": "", "萬": "", "一": ""}
# 檢查字符串是否包含“億”
if "億" in s:
yi_index = s.index("億")
result["億"] = s[:yi_index]
# 檢查億后面的部分是否包含“萬”
after_yi = s[yi_index + 1:]
if "萬" in after_yi:
wan_index = after_yi.index("萬")
result["萬"] = after_yi[:wan_index]
result["一"] = after_yi[wan_index + 1:]
else:
# 如果沒有“萬”,則億與萬中間的字符串為空,萬后面的字符串為億后面的所有內容
result["萬"] = ""
result["一"] = after_yi
else:
# 如果沒有“億”,檢查是否包含“萬”
if "萬" in s:
wan_index = s.index("萬")
result["一"] = s[wan_index + 1:]
result["萬"] = s[:wan_index]
else:
# 如果沒有“萬”,則萬后面的字符串為空,億前面的字符串為整個字符串
result["一"] = s
result["萬"] = ""
return result
def convert_amounts(amount_list):
pattern = re.compile(
r'([壹貳叁肆伍陸柒捌玖零拾佰仟萬億]+)元?((?:零|[壹貳叁肆伍陸柒捌玖]+)角)?((?:零|[壹貳叁肆伍陸柒捌玖]+)分)?')
converted_list = []
for amount in amount_list:
number = 0
match = pattern.findall(amount)
if match:
yuan, jiao, fen = match[0]
ret_yuan = extract_parts_yi_wan(yuan)
for k, v in ret_yuan.items():
new_number = 0
if v:
new_number = chinese_to_number(v)
if k == "億":
new_number *= 100000000
elif k == "萬":
new_number *= 10000
number += new_number
if jiao and jiao != '零角':
number += chinese_to_arabic[jiao.replace('角', '')] * 0.1
if fen and fen != '零分':
number += chinese_to_arabic[fen.replace('分', '')] * 0.01
converted_list.append(f"{number:.2f}")
else:
converted_list.append("無法轉換")
return converted_list
amounts = ['貳拾捌萬壹仟柒佰伍拾伍元壹角玖分', '貳拾伍萬捌仟肆佰玖拾壹元']
converted_amounts = convert_amounts(amounts)
print(converted_amounts)
以上就是Python實現(xiàn)中文大寫金額轉阿拉伯數(shù)字的詳細內容,更多關于Python中文大寫轉阿拉伯數(shù)字的資料請關注腳本之家其它相關文章!
相關文章
在VScode中配置Python開發(fā)環(huán)境的超詳細指南
在使用VSCode編寫Python代碼前,我們需要先配置Python環(huán)境,這篇文章主要給大家介紹了關于在VScode中配置Python開發(fā)環(huán)境的相關資料,需要的朋友可以參考下2023-12-12
在python tkinter中Canvas實現(xiàn)進度條顯示的方法
今天小編就為大家分享一篇在python tkinter中Canvas實現(xiàn)進度條顯示的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python3中編碼與解碼之Unicode與bytes的講解
今天小編就為大家分享一篇關于Python3中編碼與解碼之Unicode與bytes的講解,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02

