abbreviator.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. class Abbreviator:
  2. """
  3. Abbreviates strings to target_length
  4. """
  5. def __init__(self, target_length: int):
  6. if target_length < 1:
  7. raise ValueError("target_length must be greater than 0.")
  8. self.target_len = target_length
  9. def abbreviate(self, input_sent) -> str:
  10. """
  11. Abbreviates an input string, prioritizing minimizing length of longest word.
  12. Given instance `target_length` smaller than possible with min token word length of 1,
  13. returns smallest possible output given max per-token length of 1.
  14. :param input_sent
  15. :return: str string of abbreviated words
  16. """
  17. current_length = len(input_sent)
  18. if current_length <= self.target_len:
  19. return input_sent
  20. words = {word: i for i, word in enumerate(input_sent.split())}
  21. # store result list for downstream in-place token replacement
  22. result = [word for word in words]
  23. while current_length > self.target_len:
  24. sorted_words = [word for word in sorted(words.keys(), key=len, reverse=True)]
  25. longest_word = sorted_words[0]
  26. if len(longest_word) == 1:
  27. return self._re_assemble(words, result)
  28. words[longest_word[:-1]] = words.pop(longest_word)
  29. current_length -= 1
  30. if current_length <= self.target_len:
  31. return self._re_assemble(words, result)
  32. for k, v in words.items():
  33. result[v] = k
  34. return ' '.join(result)
  35. @staticmethod
  36. def _re_assemble(words, result):
  37. """
  38. Re-assembles list of words into a string in original order
  39. :param words:
  40. :param result:
  41. :return:
  42. """
  43. for k, v in words.items():
  44. result[v] = k
  45. return ' '.join(result)