I have a sentence with plain numbers and ordinal numbers and I wanted to convert ordinal digits to words like 2 nd to Second, 56 th to Fifty sixth. I used the library num2words and below code works perfectly.
import num2words
text = "ordinal numbers are like as 42 nd, 67 th, and 5 th and plain numbers such as 1, 2, 3."
numbers = re.findall('(\d+ )[st|nd|rd|th]', text)
numbers
for n in numbers:
ordinalAsString = num2words.num2words(n, ordinal=True)
print(ordinalAsString)
#forty-second
#sixty-seventh
#fifth
Now I want to create a lambda function such that,
sentence = "ordinal numbers are like as 42 nd, 67 th, and 5 th and plain numbers such as 1, 2, 3."
o/p sentence = "ordinal numbers are like as fourty-second, sixty-seventh, and fifth and plain numbers such as 1, 2, 3."
I wrote the function like this,
sentence = re.sub(r"(\d+ )[st|nd|rd|th]", lambda x: num2words.num2words(str(x), ordinal=True), sentence)
But that throws an error like,
InvalidOperation: [<class 'decimal.ConversionSyntax'>]
What is wrong in the code?
str(x)isn't going to give you the string you want;x.group(1)will.[st|nd|rd|th]also does not match what you think it does; it's equivalent to[st|ndrh], with the|acting as a literal character, not an alternation operator.st,nd,rd, orth; it's matching one ofs,t,|,n,d,r, orh.(?:st|nd|rd|th).(st|nd|rd|th)would work as well, but no use making it a capture group if you don't need to use the captured suffix.