python – How to convert numbers to words without using num2word library?
python – How to convert numbers to words without using num2word library?
You can make this much simpler by using one dictionary and a try/except clause like this:
num2words = {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, 20: Twenty, 30: Thirty, 40: Forty,
50: Fifty, 60: Sixty, 70: Seventy, 80: Eighty,
90: Ninety, 0: Zero}
>>> def n2w(n):
try:
print num2words[n]
except KeyError:
try:
print num2words[n-n%10] + num2words[n%10].lower()
except KeyError:
print Number out of range
>>> n2w(0)
Zero
>>> n2w(13)
Thirteen
>>> n2w(91)
Ninetyone
>>> n2w(21)
Twentyone
>>> n2w(33)
Thirtythree
Are you allowed to use other packages? This one works really well for me:
Inflect. It is useful for natural language generation and has a method for turning numbers into english text.
I installed it with
$ pip install inflect
Then in your Python session
>>> import inflect
>>> p = inflect.engine()
>>> p.number_to_words(1234567)
one million, two hundred and thirty-four thousand, five hundred and sixty-seven
>>> p.number_to_words(22)
twenty-two
python – How to convert numbers to words without using num2word library?
Your first statement logic is incorrect. Unless Number
is 1 or smaller, that statement is always True; 200 is greater than 1 as well.
Use and
instead, and include 1
in the acceptable values:
if (Number >= 1) and (Number <= 19):
You could use chaining as well:
if 1 <= Number <= 19:
For numbers of 20 or larger, use divmod()
to get both the number of tens and the remainder:
tens, remainder = divmod(Number, 10)
Demo:
>>> divmod(42, 10)
(4, 2)
then use those values to build your number from the parts:
return num2words2[tens - 2] + - + num2words1[below_ten]
Dont forget to account for cases when the number is above 20 and doesnt have a remainder from the divmod operation:
return num2words2[tens - 2] + - + num2words1[remainder] if remainder else num2words2[tens - 2]
All put together:
def number(Number):
if 0 <= Number <= 19:
return num2words1[Number]
elif 20 <= Number <= 99:
tens, remainder = divmod(Number, 10)
return num2words2[tens - 2] + - + num2words1[remainder] if remainder else num2words2[tens - 2]
else:
print(Number out of implemented range of numbers.)