已解决(Python cn2an库实现中文数字与阿拉伯数字互转)ValueError: mode 仅支持 [‘low‘, ‘up‘, ‘rmb‘, ‘direct‘]
报错内容
我的代码:
import re
import cn2an
a = ['1百23', '一万二', '37.30万', '五千三百二十', '24910.16', '5000.00']
for i in a:
output = cn2an.an2cn(i, "smart")
print(output)
报错信息:
raise ValueError(f"mode 仅支持 {
str(self.mode_list)} !")
ValueError: mode 仅支持 ['low', 'up', 'rmb', 'direct'] !
报错问题
报错内容翻译:值错误:模式仅支持 [“低”,“上”,“人民币”,“直接”]
报错原因:cn2an.an2cn
是将阿拉伯数字转化为小写的中文数字,并不能将中文数字转换为阿拉伯数字
解决方法
cn2an.cn2an(inputs,mode)
才是将中文数字转阿拉伯数字。
参数解读:
inputs
类型为字符串,需要转换的字符串mode
类型为字符串,mode仅支持strict
(严格模式),normal
(正常模式),smart
(灵活模式)等三个值。
修改代码为:
import re
import cn2an
a = ['1百23', '一万二', '37.30万', '五千三百二十', '24910.16', '5000.00']
for i in a:
output = cn2an.cn2an(i, "smart")
print(output)
再次运行成功:
123
12000
373000
5320
24910.16
5000.0
import re
import cn2an
# 一、实现中文数字转阿拉伯数字
a = ['1百23', '一万二', '37.30万', '五千三百二十', '24910.16', '5000.00']
for i in a:
output = cn2an.cn2an(i, "smart")
print(output)
print("-"*30)
# 二、句子中的数字转换与提取
b = ['赔偿经济损失人民币37.30万元', '赔偿差旅费五千三百二十元', '赔偿损失24910.16元', '赔偿经济损失(含合理支出)5000.00元']
for i in b:
output = cn2an.transform(i)
print(output)
money = re.findall("\d*\.*\d*万*", output)
money = ''.join(money)
money = cn2an.cn2an(money, "smart")
print(money)
123
12000
373000
5320
24910.16
5000.0
------------------------------
WARN: 不符合格式的数据:万
赔偿经济损失人民币37.30万元
373000
赔偿差旅费5320元
5320.0
赔偿损失24910.16元
24910.16
赔偿经济损失(含合理支出)5000.00元
5000.0