Skip to content

Instantly share code, notes, and snippets.

@cnu
Created July 29, 2008 05:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cnu/3018 to your computer and use it in GitHub Desktop.
Save cnu/3018 to your computer and use it in GitHub Desktop.
def singularize(word):
"""Return the singular form of a word
>>> singularize('rabbits')
'rabbit'
>>> singularize('potatoes')
'potato'
>>> singularize('leaves')
'leaf'
>>> singularize('knives')
'knife'
>>> singularize('spies')
'spy'
"""
sing_rules = [lambda w: w[-3:] == 'ies' and w[:-3] + 'y',
lambda w: w[-4:] == 'ives' and w[:-4] + 'ife',
lambda w: w[-3:] == 'ves' and w[:-3] + 'f',
lambda w: w[-2:] == 'es' and w[:-2],
lambda w: w[-1:] == 's' and w[:-1],
lambda w: w,
]
word = word.strip()
singleword = [f(word) for f in sing_rules if f(word) is not False][0]
return singleword
def _test():
import doctest
doctest.testmod()
if __name__ == '__main__':
_test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment