text.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import absolute_import
  2. from pprint import pformat
  3. def abbr(S, max, ellipsis="..."):
  4. if S is None:
  5. return "???"
  6. if len(S) > max:
  7. return ellipsis and (S[:max - len(ellipsis)] + ellipsis) or S[:max]
  8. return S
  9. def abbrtask(S, max):
  10. if S is None:
  11. return "???"
  12. if len(S) > max:
  13. module, _, cls = S.rpartition(".")
  14. module = abbr(module, max - len(cls) - 3, False)
  15. return module + "[.]" + cls
  16. return S
  17. def indent(t, indent=0):
  18. """Indent text."""
  19. return "\n".join(" " * indent + p for p in t.split("\n"))
  20. def truncate(text, maxlen=128, suffix='...'):
  21. """Truncates text to a maximum number of characters."""
  22. if len(text) >= maxlen:
  23. return text[:maxlen].rsplit(" ", 1)[0] + suffix
  24. return text
  25. def pluralize(n, text, suffix='s'):
  26. if n > 1:
  27. return text + suffix
  28. return text
  29. def pretty(value, width=80, nl_width=80, **kw):
  30. if isinstance(value, dict):
  31. return "{\n %s" % (pformat(value, 4, nl_width)[1:])
  32. elif isinstance(value, tuple):
  33. return "\n%s%s" % (' ' * 4, pformat(value, width=nl_width, **kw))
  34. else:
  35. return pformat(value, width=width, **kw)