Code for this:
>>>def handel_upto_99(number):
predef={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",14:"fourteen",15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen",20:"twenty",30:"thirty",40:"fourty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety",100:"hundred",100000:"lakh",10000000:"crore",1000000:"million",1000000000:"billion"}
if number in predef.keys():
return predef[number]
else:
return predef[(number/10)*10]+' '+predef[number%10]
>>>def return_bigdigit(number,devideby):
predef={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",14:"fourteen",15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen",20:"twenty",30:"thirty",40:"fourty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety",100:"hundred",1000:"thousand",100000:"lakh",10000000:"crore",1000000:"million",1000000000:"billion"}
if devideby in predef.keys():
return predef[number/devideby]+" "+predef[devideby]
else:
devideby/=10
return handel_upto_99(number/devideby)+" "+predef[devideby]
>>>def mainfunction(number):
dev={100:"hundred",1000:"thousand",100000:"lakh",10000000:"crore",1000000000:"billion"}
if number is 0:
return "Zero"
if number<100:
result=handel_upto_99(number)
else:
result=""
while number>=100:
devideby=1
length=len(str(number))
for i in range(length-1):
devideby*=10
if number%devideby==0:
if devideby in dev:
return handel_upto_99(number/devideby)+" "+ dev[devideby]
else:
return handel_upto_99(number/(devideby/10))+" "+ dev[devideby/10]
res=return_bigdigit(number,devideby)
result=result+' '+res
if devideby not in dev:
number=number-((devideby/10)*(number/(devideby/10)))
number=number-devideby*(number/devideby)
if number <100:
result = result + ' '+ handel_upto_99(number)
return result
result:
>>>mainfunction(12345)
' twelve thousand three hundred fourty five'
>>>mainfunction(2000)
'two thousand'
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module. Installation One can easily install num2words using pip.
pip install num2words
Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest.
In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app. ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites.
In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line. Below is the sample usage of the tool.
Python
from
num2words
import
num2words
print
(num2words(
36
))
print
(num2words(
36
, to
=
'ordinal'
))
print
(num2words(
36
, to
=
'ordinal_num'
))
print
(num2words(
36
, to
=
'year'
))
print
(num2words(
36
, to
=
'currency'
))
print
(num2words(
36
, lang
=
'es'
))
Output:
thirty-six thirty-sixth 36th zero euro, thirty-six cents treinta y seis
Time complexity: O(1).
Auxiliary space: O(1).
Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages. References: https://pypi.org/project/num2words/
Like Article
Save Article
num2words library — Convert numbers to words in multiple languages
num2words
is a library that converts numbers like 42
to words like forty-two
.
It supports multiple languages (see the list below for full list
of languages) and can even generate ordinal numbers like forty-second
(although this last feature is a bit buggy for some languages at the moment).
The project is hosted on GitHub. Contributions are welcome.
Installation
The easiest way to install num2words
is to use pip:
pip install num2words
Otherwise, you can download the source package and then execute:
python setup.py install
The test suite in this library is new, so it’s rather thin, but it can be run with:
python setup.py test
To run the full CI test suite which includes linting and multiple python environments:
pip install tox tox
Usage
Command line:
$ num2words 10001 ten thousand and one $ num2words 24,120.10 twenty-four thousand, one hundred and twenty point one $ num2words 24,120.10 -l es veinticuatro mil ciento veinte punto uno $num2words 2.14 -l es --to currency dos euros con catorce céntimos
In code there’s only one function to use:
>>> from num2words import num2words >>> num2words(42) forty-two >>> num2words(42, to='ordinal') forty-second >>> num2words(42, lang='fr') quarante-deux
Besides the numerical argument, there are two main optional arguments, to:
and lang:
to: The converter to use. Supported values are:
cardinal
(default)ordinal
ordinal_num
year
currency
lang: The language in which to convert the number. Supported values are:
en
(English, default)am
(Amharic)ar
(Arabic)az
(Azerbaijani)cz
(Czech)de
(German)dk
(Danish)en_GB
(English — Great Britain)en_IN
(English — India)en_NG
(English — Nigeria)es
(Spanish)es_CO
(Spanish — Colombia)es_VE
(Spanish — Venezuela)es_GT
(Spanish — Guatemala)eu
(EURO)fa
(Farsi)fi
(Finnish)fr
(French)fr_CH
(French — Switzerland)fr_BE
(French — Belgium)fr_DZ
(French — Algeria)he
(Hebrew)hu
(Hungarian)id
(Indonesian)is
(Icelandic)it
(Italian)ja
(Japanese)kn
(Kannada)ko
(Korean)kz
(Kazakh)lt
(Lithuanian)lv
(Latvian)no
(Norwegian)pl
(Polish)pt
(Portuguese)pt_BR
(Portuguese — Brazilian)sl
(Slovene)sr
(Serbian)sv
(Swedish)ro
(Romanian)ru
(Russian)te
(Telugu)tg
(Tajik)tr
(Turkish)th
(Thai)vi
(Vietnamese)nl
(Dutch)uk
(Ukrainian)
You can supply values like fr_FR
; if the country doesn’t exist but the
language does, the code will fall back to the base language (i.e. fr
). If
you supply an unsupported language, NotImplementedError
is raised.
Therefore, if you want to call num2words
with a fallback, you can do:
try: return num2words(42, lang=mylang) except NotImplementedError: return num2words(42, lang='en')
Additionally, some converters and languages support other optional arguments
that are needed to make the converter useful in practice.
Wiki
For additional information on some localization please check the Wiki.
And feel free to propose wiki enhancement.
History
num2words
is based on an old library, pynum2word
, created by Taro Ogawa
in 2003. Unfortunately, the library stopped being maintained and the author
can’t be reached. There was another developer, Marius Grigaitis, who in 2011
added Lithuanian support, but didn’t take over maintenance of the project.
I am thus basing myself on Marius Grigaitis’ improvements and re-publishing
pynum2word
as num2words
.
Virgil Dupras, Savoir-faire Linux
num2words
— библиотека, которая переводит числа (например, 42) в слова (сорок два) или даже в порядковые числительные (сорок второй).
Очень проста в использовании:
from num2words import num2words
print(num2words(42)) # Выведет forty-two
print(num2words(42, to='ordinal')) # Выведет forty-second
print(num2words(42, lang='fr')) # Выведет quarante-deux
Помимо основного аргумента-числа есть необязательные, дополнительные аргументы:
-
Аргумент to может принимать следущие значения:
"cardinal"
— просто перевод в число:2019
—>two thousand and nineteen
."ordinal"
— перевод в порядковое числительное:2019
—>two thousand and nineteenth
."ordinal_num"
— оставить числом:2019
—>2019th
."year"
— в год:2019
—>twenty nineteen
"currency"
— в евро:2019
—>twenty euro, nineteen cents
-
lang — определяет в какой язык переводить:
"en"
(English, default)"ar"
(Arabic)"cz"
(Czech)"de"
(German)"dk"
(Danish)"en_GB"
(English — Great Britain)"en_IN"
(English — India)"es"
(Spanish)"es_CO"
(Spanish — Colombia)"es_VE"
(Spanish — Venezuela)"eu"
(EURO)"fi"
(Finnish)"fr"
(French)"fr_CH"
(French — Switzerland)"fr_BE"
(French — Belgium)"fr_DZ"
(French — Algeria)"he"
(Hebrew)"id"
(Indonesian)"it"
(Italian)"ja"
(Japanese)"ko"
(Korean)"lt"
(Lithuanian)"lv"
(Latvian)"no"
(Norwegian)"pl"
(Polish)"pt"
(Portuguese)"pt_BR"
(Portuguese — Brazilian)"sl"
(Slovene)"sr"
(Serbian)"ro"
(Romanian)"ru"
(Russian)"sl"
(Slovene)"tr"
(Turkish)"th"
(Thai)"vi"
(Vietnamese)"nl"
(Dutch)"uk"
(Ukrainian)
Некоторые коды состоят из языка и страны: fr_FR
. Если страна не поддерживается, но поддерживается язык, то программа использует код языка: fr
. Если вы используете язык не из этого списка, получите NotImplementedError
.
Попробуйте бесплатные уроки по Python
Получите крутое код-ревью от практикующих программистов с разбором ошибок и рекомендациями, на что обратить внимание — бесплатно.
Переходите на страницу учебных модулей «Девмана» и выбирайте тему.
Converting a number to words is the process of translating a number to words and is an easy process. However, A few rules must be followed when converting a number to words, such as using the correct order and the correct spelling of numbers.
Converting numbers into words has many benefits, such as :
- It helps in understanding and remembering large numbers.
- It makes it easier to write and read numbers.
- Useful in many applications, such as writing cheques or displaying numbers on a screen.
In Python, this can be achieved using the following ways:
1
Using the Num2Word library
To convert numbers into words using the num2word library, we first have to import the num2word library. And after that, take a number as input from the user using the input() function.
import num2word
num = int(input("Enter a number: "))
Now, to convert the given number into words, use the word() function provided by the num2word module, and after that, print the final result.
word_number = num2word.word(num)
print(word_number)
Here is the complete code in action :
import num2word
num = int(input("Enter a number: "))
word_number = num2word.word(num)
print(word_number)
'''
#Output
Enter a number: 653
Six Hundred Fifty Three
'''
2
Using the inflect library
The inflect library is a library for singularizing and pluralizing English words. It can be used to convert a number to its ordinal form, as well as to convert a number to its word form.
To convert a number to its word form, we can use the number_to_words() method. This method takes an integer as an argument and returns a string. For example, the number_to_words() method will convert the number 100 to its word form, i.e., “one hundred”.
Here is the python code that uses the inflect library to convert a number to its word form.
import inflect
number = int(input("Enter the number : "))
p = inflect.engine()
word = p.number_to_words(number)
print(number,":",word)
'''
#Output
Enter the number : 777
777 : seven hundred and seventy-seven
'''
3
Creating custom function
Till now, we have seen the readymade module that Python offers. Now, let’s write a function to translate a number into its corresponding English word representation.
For that, We will first need to break the number down into its constituent parts. We can do this by using the modulo operator (%) to find the remainder and integer division (//) to remove the last digit from the number.
And finally, we will use a series of if-elif-else statements and add a special case for the number zero.
Here is the complete code in action :
def convert_to_words(num):
if num == 0:
return "zero"
ones = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
tens = ["", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
num_string = ""
while num > 0:
if num < 10:
num_string += ones[num]
num = 0
elif num >= 10 and num <20:
num_string += teens[num%10]
num = 0
elif num < 100:
num_string += tens[num // 10]
if num % 10 != 0:
num_string += "-" + ones[num % 10]
num = 0
else: #num < 1000:
num_string += ones[num // 100] + " hundred "
num %= 100
return num_string
num = int(input("Enter any number less than 1000 : "))
print(num," : ",convert_to_words(num))
'''
Enter any number less than 1000 : 54
54 : fifty-four
'''
Using a dictionary to get the English word representation of any given number is another approach; Here, we are declaring the python dictionary, which holds the value and keys.
And a convert_to_words() method takes one parameter i.e., number. And after that function does the main part of converting that number to its word form.
Here is the complete code in action.
#program to convert number into words in Python using a dictionary
number_words = {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', 100: 'hundred', 1000: 'thousand'}
def convert_to_words(number):
if number == 0:
return 'zero'
if number < 0:
return 'minus ' + convert_to_words(-number)
if number < 21:
return number_words[number]
if number < 100:
return number_words[number // 10 * 10] + ' ' + number_words[number % 10]
if number < 1000:
return number_words[number // 100] + ' ' + number_words[100] + ' ' + convert_to_words(number % 100)
for i, k in enumerate(number_words):
if number < 1000 ** (i + 1):
return number_words[number // 1000 ** i] + ' ' + number_words[1000 ** i] + ' ' + convert_to_words(number % 1000 ** i)
number = int(input("Enter a number: "))
print(convert_to_words(number))
'''
#Output
Enter a number: 743
seven hundred forty three
'''