python - 以印度格式将金额转换为Python中的单词
问题描述
如何将印度的金额转换为单词?
我正在使用 num2words 库,但它在呈现“十万”和“千万”时呈现了错误的单词集。
例如:
num2words(903614.55, lang='en-IN')
它的印刷'nine hundred and three thousand, six hundred and fourteen point five five'
但实际的印度金额表示应该是nine lakhs three thousand six hundred fourteen and five five paisa
。
然后我尝试了以下代码:
def num2words(num):
under_20 = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen','Seventeen','Eighteen','Nineteen']
tens = ['Twenty','Thirty','Forty','Fifty','Sixty','Seventy','Eighty','Ninety']
above_100 = {100: 'Hundred',1000:'Thousand', 100000:'Lakhs', 10000000:'Crores'}
if num < 20:
return under_20[num]
if num < 100:
return tens[(int)(num/10)-2] + ('' if num%10==0 else ' ' + under_20[num%10])
# find the appropriate pivot - 'Million' in 3,603,550, or 'Thousand' in 603,550
pivot = max([key for key in above_100.keys() if key <= num])
return num2words((int)(num/pivot)) + ' ' + above_100[pivot] + ('' if num%pivot==0 else ' ' + num2words(num%pivot))
但是现在一个错误来了
TypeError:列表索引必须是整数或切片,而不是小数。十进制
我的问题是十进制数,整数工作正常。
解决方案
解决方案很简单,事后看来错误很明显。
只需在调用 num2words 时将 en-IN 替换为 en_IN。不需要任何自定义代码。我也被这个烧死了。
num2words.num2words(123456, lang='en_IN')
返回
one lakh, twenty-three thousand, four hundred and fifty-six
推荐阅读
- python - 子进程“没有这样的文件或目录”
- sql - 使用联接更新表时如何修复此 SQL 错误?
- css - 如何在响应式设计中定位圆圈并使它们保持相同的排列?
- unicode - raku 可以避免这个 Malformed UTF-8 错误吗?
- javascript - 如何在Javascript中访问函数外部的变量?
- javascript - 为什么在提交并返回视图或redirectToAction之后找不到我的javascript方法
- selenium - 自动将任务添加到新的 Btibucket 拉取请求
- python - 递归清理 json 对象时,为什么会出现“unhashable type: dict”错误?
- javascript - 使用 moment.js 进行时间转换
- woocommerce - 所见即所得不添加段落标签