Made utils.pluralize a little smarter.

This commit is contained in:
Jeremy Fincher 2003-12-02 18:58:57 +00:00
parent 9277d4113f
commit 949ea7aa2b

View File

@ -48,6 +48,7 @@ import sgmllib
import compiler import compiler
import textwrap import textwrap
import htmlentitydefs import htmlentitydefs
from itertools import imap, ifilter
from structures import TwoWayDictionary from structures import TwoWayDictionary
@ -304,16 +305,17 @@ def ellipsisify(s, n):
else: else:
return (textwrap.wrap(s, n-3)[0] + '...') return (textwrap.wrap(s, n-3)[0] + '...')
plurals = TwoWayDictionary({'match': 'matches', plurals = TwoWayDictionary({})
'patch': 'patches',
'loss': 'losses'})
def _matchCase(s1, s2): def _matchCase(s1, s2):
"""Matches the case of s1 in s2""" """Matches the case of s1 in s2"""
L = list(s2) if s1.isupper():
for (i, char) in enumerate(s1[:len(s2)]): return s2.upper()
if char.isupper(): else:
L[i] = char.upper() L = list(s2)
return ''.join(L) for (i, char) in enumerate(s1[:len(s2)]):
if char.isupper():
L[i] = char.upper()
return ''.join(L)
def pluralize(i, s): def pluralize(i, s):
"""Returns the plural of s based on its number i. Put any exceptions to """Returns the plural of s based on its number i. Put any exceptions to
@ -325,17 +327,18 @@ def pluralize(i, s):
lowered = s.lower() lowered = s.lower()
if lowered in plurals: if lowered in plurals:
return _matchCase(s, plurals[lowered]) return _matchCase(s, plurals[lowered])
elif any(lowered.endswith, ['ch', 'ss']):
return _matchCase(s, s+'es')
else: else:
if s.isupper(): return _matchCase(s, s+'s')
return s + 'S'
else:
return s + 's'
def depluralize(s): def depluralize(s):
"""Returns the singular of s.""" """Returns the singular of s."""
lowered = s.lower() lowered = s.lower()
if lowered in plurals: if lowered in plurals:
return _matchCase(s, plurals[lowered]) return _matchCase(s, plurals[lowered])
elif any(lowered.endswith, ['ches', 'sses']):
return s[:-2]
else: else:
if s.endswith('s') or s.endswith('S'): if s.endswith('s') or s.endswith('S'):
return s[:-1] # Chop off 's'. return s[:-1] # Chop off 's'.