Last active
September 27, 2022 01:36
-
-
Save Redlnn/7e9ca8cc4ca5e687156c2f926eeed1e0 to your computer and use it in GitHub Desktop.
中文数字转阿拉伯数字
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import re | |
unit_map = { | |
'京': 10**16, | |
'亿亿': 10**16, | |
'千万亿': 10**15, | |
'百万亿': 10**14, | |
'十万亿': 10**13, | |
'兆': 10**12, | |
'万亿': 10**12, | |
'千亿': 10**11, | |
'百亿': 10**10, | |
'十亿': 10**9, | |
'亿': 10**8, | |
'万': 10**4, | |
} | |
k_unit_map = {'万': 10000, '千': 1000, '仟': 1000, '百': 100, '佰': 100, '十': 10, '拾': 10} | |
num_map = { | |
'幺': 1, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, | |
'壹': 1, '贰': 2, '叁': 3, '肆': 4, '伍': 5, '陆': 6, '柒': 7, '捌': 8, '玖': 9, '零': 0, | |
} | |
def str2num(target: str) -> int: | |
for char, num in num_map.items(): | |
target = target.replace(char, str(num)) | |
return int(target) | |
def resolve(string: str) -> int: | |
num = 0 | |
for unit in k_unit_map.keys(): | |
split_result = string.split(unit, 1) | |
if len(split_result) ==1 : | |
continue | |
big = split_result[0] | |
small = split_result[1] | |
if big == '': | |
big = '一' | |
num += num_map[big] * k_unit_map[unit] | |
num += resolve(small) | |
return num | |
return num_map[string] if len(string) > 0 else 0 | |
def split(line: str) -> int: | |
num = 0 | |
for unit in unit_map.keys(): | |
if unit not in line: | |
continue | |
split_result = line.split(unit, 1) | |
if len(split_result) ==1 : | |
continue | |
big = split_result[0] | |
small = split_result[1] | |
num += resolve(big) * unit_map[unit] | |
num += split(small) | |
return num | |
return resolve(line) if num != 0 else resolve(line) | |
def main(target: str) -> int: | |
if not re.match('^[幺一二三四五六七八九壹贰叁肆伍陆柒捌玖零十百千拾佰仟万亿兆京]+$', target): | |
raise ValueError('Invalid input') | |
if next( | |
(False for k_unit in k_unit_map.keys() if k_unit in target), | |
all(unit not in target for unit in unit_map.keys()) | |
): | |
return str2num(target) | |
return split(target.replace('零', '')) | |
test = '一一四五一四一九一九八幺零' | |
print(f'输入:{test}') | |
print(f'输出:{main(test)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment