-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathordinal.py
More file actions
62 lines (49 loc) · 1.43 KB
/
ordinal.py
File metadata and controls
62 lines (49 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# ORDINAL - last updated for NodeBox 1rc7
# Author: Tom De Smedt <tomdesmedt@organisms.be>
# See LICENSE.txt for details.
# Based on the Ruby Linguistics module by Michael Granger:
# http://www.deveiate.org/projects/Linguistics/wiki/English
ordinal_nth = {
0 : "th",
1 : "st",
2 : "nd",
3 : "rd",
4 : "th",
5 : "th",
6 : "th",
7 : "th",
8 : "th",
9 : "th",
11 : "th",
12 : "th",
13 : "th",
}
ordinal_suffixes = [
["ty$" , "tieth"],
["one$" , "first"],
["two$" , "second"],
["three$" , "third"],
["five$" , "fifth"],
["eight$" , "eighth"],
["nine$" , "ninth"],
["twelve$", "twelfth"],
["$" , "th"],
]
def ordinal(number):
""" Returns the ordinal word of a given number.
For example: 103 -> 103rd, twenty-one -> twenty first.
The given number can be either integer or string,
returns None otherwise.
"""
if isinstance(number, int):
if number%100 in ordinal_nth:
return str(number) + ordinal_nth[number%100]
else:
return str(number) + ordinal_nth[number%10]
if isinstance(number, str):
import re
for suffix, inflection in ordinal_suffixes:
if re.search(suffix, number) is not None:
return re.sub(suffix, inflection, number)
#print ordinal(103)
#print ordinal("twenty-one")