I am currently looking for the way to replace words like first, second, third,...with appropriate ordinal number representation (1st, 2nd, 3rd). I have been googling for the last week and I didn't find any useful standard tool or any function from NLTK.
So is there any or should I write some regular expressions manually?
Thanks for any advice
Ordinal numbers are related to their cardinal number counterparts. In English, it is usual to add two letters to a cardinal number to represent an ordinal number. For example, the cardinal numbers 1, 2 and 3 have the ordinal versions 1st, 2nd and 3rd.
What are ordinal numbers from 1 to 10? The ordinal numbers from 1 to 10 are 1st – First, 2nd – Second, 3rd – Third, 4th – Fourth, 5th – Fifth, 6th – Sixth, 7th – Seventh, 8th – Eighth, 9th – Ninth and 10th – Tenth, respectively.
The term ordinal means countable and in the context of Python's. ord. function will return the integer value assigned to a character in the Unicode encoding system. This can be useful when converting between bytes to strings, binary to encoded representations, or sheer hobbyism.
The package number-parser can parse ordinal words ("first", "second", etc) to integers.
from number_parser import parse_ordinal
n = parse_ordinal("first")
To convert an integer to "1st", "2nd", etc, you can use the following (taken from Gareth on codegolf):
ordinal = lambda n: "%d%s" % (n,"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4])
This works on any number:
print([ordinal(n) for n in range(1,32)])
['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th',
'11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th',
'20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th',
'29th', '30th', '31st']
If you don't want to pull in an additional dependency on an external library (as suggested by luckydonald) but also don't want the future maintainer of the code to haunt you down and kill you (because you used golfed code in production) then here's a short-but-maintainable variant:
def make_ordinal(n):
'''
Convert an integer into its ordinal representation::
make_ordinal(0) => '0th'
make_ordinal(3) => '3rd'
make_ordinal(122) => '122nd'
make_ordinal(213) => '213th'
'''
n = int(n)
if 11 <= (n % 100) <= 13:
suffix = 'th'
else:
suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)]
return str(n) + suffix
How about this:
suf = lambda n: "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n%100 if (n%100)<20 else n%10,"th"))
print [suf(n) for n in xrange(1,32)]
['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th',
'11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th',
'20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th',
'29th', '30th', '31st']
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