Created
November 28, 2012 21:40
Revisions
-
Fletcher Tomalty renamed this gist
Nov 28, 2012 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,62 @@ def english_count(count, object = None, plural = None): """ Generate an English representation of the count of objects. Plural defaults to object + 's' or object[:-1] + 'ies' for objects ending in 'y'. Examples: In [2]: english_count(0, 'hat') Out[2]: 'no hats' In [4]: english_count(1, 'hat') Out[4]: '1 hat' In [5]: english_count(3, 'pastry') Out[5]: '3 pastries' In [2]: english_count(4, 'knife', 'knives') Out[2]: '4 knives' """ text = 'no' if count == 0 else str(count) if object is not None: if plural is None: if object[-1] == 'y': plural = object[:-1] + 'ies' else: plural = object + 's' text += ' ' + (object if count == 1 else plural) return text def english_list(items, and_or = 'and'): """ Generate an English representation of a list of things. Defaults to 'and' but you can also pass 'or' as the second argument. Examples: In [3]: english_list(string.uppercase) Out[3]: 'A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z' In [4]: english_list(['A', 'B'], 'or') Out[4]: 'A or B' In [6]: english_list(['A']) Out[6]: 'A' In [7]: english_list([]) Out[7]: '' """ items = [str(item) for item in items] if len(items) < 3: # Handles the edgecases of zero, one, and two items ('', 'A', 'A and B' respectively) text = (' ' + and_or + ' ').join(items) else: separator = ', ' text = separator.join(items[:-1]) text += separator + and_or + ' ' + str(items[-1]) return text