我需要构建一个函数,该函数将数字的单词表示形式作为输入并将其转换为数字。 one => 1
,threethousandsixtyhundreadtwo => 3602
等。我有数字(999,999)
的上限,并且我已经做过反向功能。我也有将要使用的所有单词。到目前为止,当数字的不同部分之间没有空格或类似内容时,我仍然坚持如何分隔数字的每个部分。
在python中执行此操作。我没有找到使用find()
的合理方法。
答案 0 :(得分:1)
使用此代码:
def int2word(number):
def num2word(num):
n = ["one",
"two",
"three",
"four",#lists
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen"]
ten = [ "twenty",
"thirty",
"forty",
"fifty",
"sixty",
"seventy",
"eighty",
"ninety",
]
if num == 0:
return ""
elif num in range(1, 19):#for nos 0 - 19
return (n[num-1])
elif num in range(20,99) and num%10 == 0:#for nos 20 - 99 that are multiples of ten
return (ten[num//10 - 2])
elif num in range(20,99)and num%10 > 0:
return (ten[num//10-2] +"-"+ n[num%10-1])
result = ""
if number == 0:
result = "zero"
else:
c = number // 10000000
if c != 0:
crores = num2word(c)
result += crores + " crore "
l = number % 10000000
if l//100000 != 0:
lakh = num2word(l//100000)
result += lakh + " lakh "
th = number%100000
if th//1000 != 0:
thos = num2word(th//1000)
result += thos + " thousand "
h = number%1000
if h//100 != 0:
huns = num2word(h//100)
result += huns + " hundred "
t = h % 100
if t != 0:
tens = num2word(t)
result += tens
return result