utils_1.py 1.1 KB

1234567891011121314151617181920212223242526
  1. def truncate_sentence(text, max_chars, break_words=False, padding=0):
  2. """Truncates a sentence.
  3. :param max_chars: The maximum characters of truncated sentence.
  4. :param break_words: If you wish to truncate given sentence strictly even
  5. if it breaks a word, set it to ``True``. It defaults
  6. to ``False`` which means truncating given sentence
  7. shorter but never breaking words.
  8. :param padding: The padding size for truncating. It is usually used to
  9. keep spaces for some ending characters such as ``"..."``.
  10. :return: The truncated sentence.
  11. """
  12. if break_words:
  13. return text[:-abs(max_chars - len(text)) - padding]
  14. words = []
  15. for word in text.split():
  16. predicted_len = (
  17. sum(map(len, words)) + # length of words
  18. len(word) + # length of next word
  19. len(words) - 1 + # length of spaces
  20. padding)
  21. if predicted_len >= max_chars:
  22. break
  23. words.append(word)
  24. return ' '.join(words)