The input is a sentence containing words, numbers and ordinal numbers such as 1st
, 2nd
, 60th
and etc.
The output should contain only words. For example:
1st
→ first
2nd
→ second
60th
→ sixtieth
523rd
→ five hundred twenty-third
num2words
converts the numbers to words. But it does not work for ordinal terms such as 1st
, 2nd
, 60th
and etc.
How is possible to use python to turn ordinal numbers into words?
With num2words
, you should be using ordinal=True
to get the output you desire, as noted in its documentation:
from num2words import num2words
print(num2words(1, ordinal=True))
print(num2words(2, ordinal=True))
print(num2words(60, ordinal=True))
print(num2words(523, ordinal=True))
prints:
first
second
sixtieth
five hundred and twenty-third
import re
from num2words import num2words
def replace_ordinal_numbers(text):
re_results = re.findall('(\d+(st|nd|rd|th))', text)
for enitre_result, suffix in re_results:
num = int(enitre_result[:-len(suffix)])
text = text.replace(enitre_result, num2words(num, ordinal=True))
return text
def replace_numbers(text):
re_results = re.findall('\d+', text)
for term in re_results:
num = int(term)
text = text.replace(term, num2words(num))
return text
def convert_numbers(text):
text = replace_ordinal_numbers(text)
text = replace_numbers(text)
return text
if __name__ == '__main__':
assert convert_numbers('523rd') == 'five hundred and twenty-third'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With