From 2ffe5a13ddc92c08ce106e14e857cd7f3385998c Mon Sep 17 00:00:00 2001 From: Jeremy Fincher Date: Thu, 16 Oct 2003 20:05:45 +0000 Subject: [PATCH] Added depluralize function and fixed latent (untested) capitalization buggerishness. --- src/utils.py | 33 +++++++++++++++++++++++++++++---- test/test_utils.py | 19 +++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/utils.py b/src/utils.py index 3a5108a42..642ab065d 100755 --- a/src/utils.py +++ b/src/utils.py @@ -44,6 +44,8 @@ import sgmllib import textwrap import htmlentitydefs +from structures import TwoWayDictionary + def normalizeWhitespace(s): """Normalizes the whitespace in a string; \s+ becomes one space.""" return ' '.join(s.split()) @@ -286,7 +288,16 @@ def ellipsisify(s, n): else: return (textwrap.wrap(s, n-3)[0] + '...') -plurals = {'match': 'matches'} +plurals = TwoWayDictionary({'match': 'matches', + 'patch': 'patches',}) +def _matchCase(s1, s2): + """Matches the case of s1 in s2""" + L = list(s2) + for (i, char) in enumerate(s1[:len(s2)]): + if char.isupper(): + L[i] = char.upper() + return ''.join(L) + def pluralize(i, s): """Returns the plural of s based on its number i. Put any exceptions to the general English rule of appending 's' in the plurals dictionary. @@ -294,10 +305,24 @@ def pluralize(i, s): if i == 1: return s else: - if s in plurals: - return plurals[s] + lowered = s.lower() + if lowered in plurals: + return _matchCase(s, plurals[lowered]) else: - return s + 's' + if s.isupper(): + return s + 'S' + else: + return s + 's' + +def depluralize(s): + lowered = s.lower() + if lowered in plurals: + return _matchCase(s, plurals[lowered]) + else: + if s.endswith('s') or s.endswith('S'): + return s[:-1] # Chop off 's'. + else: + return s # Don't know what to do. def nItems(n, item, between=None): """Works like this: diff --git a/test/test_utils.py b/test/test_utils.py index a3abbc289..d65c94ef8 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -36,6 +36,25 @@ import utils class UtilsTest(unittest.TestCase): + def testPluralize(self): + f = utils.pluralize + self.assertEqual('bike', f(1, 'bike')) + self.assertEqual('bikes', f(2, 'bike')) + self.assertEqual('BIKE', f(1, 'BIKE')) + self.assertEqual('BIKES', f(2, 'BIKE')) + self.assertEqual('match', f(1, 'match')) + self.assertEqual('matches', f(2, 'match')) + self.assertEqual('Patch', f(1, 'Patch')) + self.assertEqual('Patches', f(2, 'Patch')) + + def testDepluralize(self): + f = utils.depluralize + self.assertEqual('bike', f('bikes')) + self.assertEqual('Bike', f('Bikes')) + self.assertEqual('BIKE', f('BIKES')) + self.assertEqual('match', f('matches')) + self.assertEqual('Match', f('Matches')) + def testTimeElapsed(self): self.assertRaises(ValueError, utils.timeElapsed, 0, 0, seconds=False) then = 0