Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordinal number to words in Python

Tags:

python

The problem

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:

  • 1stfirst
  • 2ndsecond
  • 60thsixtieth
  • 523rdfive hundred twenty-third

What I have tried

num2words converts the numbers to words. But it does not work for ordinal terms such as 1st, 2nd, 60th and etc.

The question

How is possible to use python to turn ordinal numbers into words?

like image 557
Michael Avatar asked Dec 02 '22 11:12

Michael


2 Answers

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
like image 98
asongtoruin Avatar answered Dec 09 '22 15:12

asongtoruin


The entire solution

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'
like image 34
Michael Avatar answered Dec 09 '22 15:12

Michael