Is there a way to convert number words to Integers?

前端 未结 16 2280
北恋
北恋 2020-11-22 06:14

I need to convert one into 1, two into 2 and so on.

Is there a way to do this with a library or a class or anythi

16条回答
  •  执笔经年
    2020-11-22 06:48

    This code works only for numbers below 99.
    both word to Int and int to word.
    (for rest need to implement 10-20 lines of code and simple logic. This is just simple code for beginners)
    
    
    num=input("Enter the number you want to convert : ")
    mydict={'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five','6': 'Six', '7': 'Seven', '8': 'Eight', '9': 'Nine', '10': 'Ten','11': 'Eleven', '12': 'Twelve', '13': 'Thirteen', '14': 'Fourteen', '15': 'Fifteen', '16': 'Sixteen', '17': 'Seventeen', '18': 'Eighteen', '19': 'Nineteen'}
    mydict2=['','','Twenty','Thirty','Fourty','fifty','sixty','Seventy','Eighty','Ninty']
    if num.isdigit():
        if(int(num)<20):
            print(" :---> "+mydict[num])
        else:
                var1=int(num)%10
                var2=int(num)/10
                print(" :---> "+mydict2[int(var2)]+mydict[str(var1)])
    else:
        num=num.lower();
        dict_w={'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':11,'twelve':12,'thirteen':13,'fourteen':14,'fifteen':15,'sixteen':16,'seventeen':'17','eighteen':'18','nineteen':'19'}
        mydict2=['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninty']
        divide=num[num.find("ty")+2:]
        if num:
            if(num in dict_w.keys()):
                print(" :---> "+str(dict_w[num]))
            elif divide=='' :
                    for i in range(0, len(mydict2)-1):
                       if mydict2[i] == num:
                          print(" :---> "+str(i*10))
            else :
                str3=0
                str1=num[num.find("ty")+2:]
                str2=num[:-len(str1)]
                for i in range(0, len(mydict2) ):
                    if mydict2[i] == str2:
                        str3=i;
                if str2 not in mydict2:
                    print("----->Invalid Input<-----")                
                else:
                    try:
                        print(" :---> "+str((str3*10)+dict_w[str1]))
                    except:
                        print("----->Invalid Input<-----")
        else:
                print("----->Please Enter Input<-----")
    

提交回复
热议问题