Skip to content

Instantly share code, notes, and snippets.

@mommi84
Created November 7, 2017 11:25
Show Gist options
  • Save mommi84/47ab8617d85337d6ae07a60afee995b1 to your computer and use it in GitHub Desktop.
Save mommi84/47ab8617d85337d6ae07a60afee995b1 to your computer and use it in GitHub Desktop.
Conversion from integer numbers to English words.
#!/usr/bin/env python
"""
Conversion from integer numbers to English words.
Author: Tommaso Soru <tom@tommaso-soru.it>
Example:
$ python numbers_words.py 3213213000312
threetrillionstwohundredsthirteenbillionstwohundredsthirteenmillionsthreehundredstwelve
License: https://creativecommons.org/licenses/by/4.0/
Version 0.0.1
"""
import sys
groups = ['', 'thousand', 'million', 'billion', 'trillion', 'quadrillion']
HUN = 'hundred'
ZERO = 'zero'
MINUS = 'minus'
single = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
excep = { 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', 50: 'fifty', 60: 'sixty', 70: 'seventy', 80: 'eighty', 90: 'ninety' }
def prepend(a, b):
return a + b
def numbers_words(num):
if num == 0:
return ZERO
if num > 0:
n = str(num)
else:
n = str(-num)
words = ""
for i in range(len(n) / 3 + 1):
b = len(n)-(3*i)
if b == 0:
continue
a = b - 3
if a < 0:
a = 0
p = n[a:b]
if len(p) == 1:
p = "00" + p
if len(p) == 2:
p = "0" + p
if p == "000":
continue # skip
out = ""
# exceptions
k = int(p[1:])
if k in excep:
out = prepend(excep[k], out)
else:
# units
k2 = int(p[2])
if k2 > 0:
out = prepend(single[k2], out)
# decs
if k-k2 > 0:
out = prepend(excep[k-k2], out)
# hundreds
h = int(p[0])
s = ''
if h > 1:
s = 's' # plural
if h > 0:
out = prepend(single[h] + HUN + s, out)
gr = groups[i]
if int(p) > 1 and i > 0:
gr += 's' # plural
out = prepend(out, gr)
words = prepend(out, words)
if num < 0:
words = prepend(MINUS, words) # negative
return words
print numbers_words(int(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment