Skip to content

Instantly share code, notes, and snippets.

@jseidl
Created April 10, 2014 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jseidl/10385375 to your computer and use it in GitHub Desktop.
Save jseidl/10385375 to your computer and use it in GitHub Desktop.
Convert textual representation of numbers (twenty two) into integers (22)
def number_text_to_integer(self, text):
parts = text.split(' ')
accumulator = 0
oper = 'sum'
units = ['','one','two','three','four','five','six','seven','eight','nine']
teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen']
tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy', 'eighty','ninety', 'hundred']
thousands = ['','thousand','million','billion','trillion','quadrillion', 'quintillion','sextillion','septillion','octillion', 'nonillion','decillion','undecillion','duodecillion', 'tredecillion','quattuordecillion','sexdecillion', 'septendecillion','octodecillion','novemdecillion', 'vigintillion']
number = []
totals = []
for part in parts:
oper = 'sum'
nr = 0
if part in units:
nr = units.index(part)
if part in tens:
nr = int("%d0" % tens.index(part))
if part == 'hundred':
oper = 'times'
if part in teens:
nr = int("1%d" % teens.index(part))
if part in thousands:
nr = int(1000**thousands.index(part))
oper = 'times'
if oper == 'sum':
accumulator += nr
elif oper == 'times':
if accumulator == 0:
accumulator = 1
accumulator *= nr
totals.append(accumulator)
accumulator = 0
number.append(nr)
totals.append(accumulator)
return sum(totals)
print number_text_to_integer('one')
print number_text_to_integer('four')
print number_text_to_integer('ten')
print number_text_to_integer('eleven')
print number_text_to_integer('twelve')
print number_text_to_integer('twenty')
print number_text_to_integer('twenty two')
print number_text_to_integer('two hundred')
print number_text_to_integer('four hundred twenty two')
print number_text_to_integer('four thousand twenty two')
print number_text_to_integer('four thousand three hundred ninety two')
print number_text_to_integer('ten million four thousand three hundred ninety two')
print number_text_to_integer('ninety billion ten million four thousand three hundred ninety two')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment