Python 将 中文数字 转换为 阿拉伯数字
你可以使用正则表达式和字典来实现将中文数字转换为阿拉伯数字的任务。
import re
# 定义数字字典
num_dict = {
'零': 0,
'一': 1,
'二': 2,
'三': 3,
'四': 4,
'五': 5,
'六': 6,
'七': 7,
'八': 8,
'九': 9
}
# 定义要替换的字符串
str_to_replace = '二○○三'
# 使用正则表达式匹配数字
pattern = re.compile(r'[零一二三四五六七八九]+')
nums = pattern.findall(str_to_replace)
# 将数字替换为阿拉伯数字
for num in nums:
str_to_replace = str_to_replace.replace(num, str(num_dict[num]))
print(str_to_replace)
输出结果为:
2003
注意,这个方法只适用于中文数字与阿拉伯数字一一对应的情况。如果有其他情况,可能需要修改字典或正则表达式。
原文地址: https://www.cveoy.top/t/topic/oAXw 著作权归作者所有。请勿转载和采集!