Last active
October 15, 2015 15:05
-
-
Save saul/1effecb06e679e3ca7e6 to your computer and use it in GitHub Desktop.
Textualise an integer to natural English language in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def slice_number(num, skip_places, num_places): | |
num //= 10**skip_places | |
return num - ((num // 10**num_places) * 10**num_places) | |
def textualise_number(num): | |
number_text = { | |
0: 'zero', | |
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', | |
15: 'fifteen', | |
} | |
special_tens = { | |
20: 'twenty', | |
30: 'thirty', | |
50: 'fifty', | |
} | |
if num < 100: | |
out = [] | |
lsd = slice_number(num, 0, 1) | |
second_lsd = slice_number(num, 1, 1) | |
ten = second_lsd * 10 | |
if num in number_text: | |
return number_text[num] | |
if 10 < num < 20: | |
return number_text[lsd].rstrip('t') + 'teen' | |
if ten in special_tens: | |
out.append(special_tens[ten]) | |
elif second_lsd > 0: | |
out.append(number_text[second_lsd].rstrip('t') + 'ty') | |
out.append(number_text[lsd]) | |
return ' '.join(out) | |
out = [] | |
slices = [ | |
(0, 2, ''), | |
(2, 1, 'hundred'), | |
(3, 3, 'thousand'), | |
(6, 3, 'million'), | |
(9, 3, 'billion'), | |
(12, 3, 'trillion'), | |
(15, 3, 'quadrillion'), | |
] | |
for skip_places, num_places, suffix in slices: | |
if 10**skip_places > num: | |
continue | |
sliced = slice_number(num, skip_places, num_places) | |
if sliced == 0: | |
continue | |
textualised = textualise_number(sliced) | |
if not suffix: | |
out.insert(0, 'and ' + textualised) | |
continue | |
out.insert(0, textualised + ' ' + suffix) | |
return ' '.join(out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment