python实现将英文单词表示的数字转换成阿拉伯数字的方法
本文实例讲述了python实现将英文单词表示的数字转换成阿拉伯数字的方法。分享给大家供大家参考。具体实现方法如下:
importre _known={ 'zero':0, '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, 'twenty':20, 'thirty':30, 'forty':40, 'fifty':50, 'sixty':60, 'seventy':70, 'eighty':80, 'ninety':90 } defspoken_word_to_number(n): """Assumenisapositiveinteger". assert_positive_integer_number('ninehundred')==900 assertspoken_word_to_number('onehundred')==100 assertspoken_word_to_number('eleven')==11 assertspoken_word_to_number('twentytwo')==22 assertspoken_word_to_number('thirty-two')==32 assertspoken_word_to_number('fortytwo')==42 assertspoken_word_to_number('twohundredthirtytwo')==232 assertspoken_word_to_number('twothirtytwo')==232 assertspoken_word_to_number('nineteenhundredeightynine')==1989 assertspoken_word_to_number('nineteeneightynine')==1989 assertspoken_word_to_number('onethousandninehundredandeightynine')==1989 assertspoken_word_to_number('nineeighty')==980 assertspoken_word_to_number('ninetwo')==92#wontbeabletoconvertthisone assertspoken_word_to_number('ninethousandninehundred')==9900 assertspoken_word_to_number('onethousandninehundredone')==1901 """ n=n.lower().strip() ifnin_known: return_known[n] else: inputWordArr=re.split('[-]',n) assertlen(inputWordArr)>1#allsinglewordsareknown #Checkthepathologicalcasewherehundredisattheendorthousandisatend ifinputWordArr[-1]=='hundred': inputWordArr.append('zero') inputWordArr.append('zero') ifinputWordArr[-1]=='thousand': inputWordArr.append('zero') inputWordArr.append('zero') inputWordArr.append('zero') ifinputWordArr[0]=='hundred': inputWordArr.insert(0,'one') ifinputWordArr[0]=='thousand': inputWordArr.insert(0,'one') inputWordArr=[wordforwordininputWordArrifwordnotin['and','minus','negative']] currentPosition='unit' prevPosition=None output=0 forwordinreversed(inputWordArr): ifcurrentPosition=='unit': number=_known[word] output+=number ifnumber>9: currentPosition='hundred' else: currentPosition='ten' elifcurrentPosition=='ten': ifword!='hundred': number=_known[word] ifnumber<10: output+=number*10 else: output+=number #else:nothingspecial currentPosition='hundred' elifcurrentPosition=='hundred': ifwordnotin['hundred','thousand']: number=_known[word] output+=number*100 currentPosition='thousand' elifword=='thousand': currentPosition='thousand' else: currentPosition='hundred' elifcurrentPosition=='thousand': assertword!='hundred' ifword!='thousand': number=_known[word] output+=number*1000 else: assert"Can'tbehere"==None return(output)
希望本文所述对大家的Python程序设计有所帮助。