translation.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. class translation:
  2. """ This ciass is responsible for single translation in the library.
  3. This store single translation, and its state. Could be casted to string
  4. and formated. When translated phrase must contain variables, that
  5. could be passed by format function, and `#{ name }` in the phrase.
  6. Attributes
  7. ----------
  8. text : str
  9. Phrase content as string.
  10. valid : bool
  11. True when phrase was translated correctly or False when not.
  12. Methods
  13. -------
  14. format(params: dict) -> dict
  15. That method could format translated phrase with given dict.
  16. """
  17. def __init__(self, content: str, success: bool = True) -> None:
  18. """ This create new translaed phrase.
  19. It require string content of the translated phrase, and also state
  20. of the translation. When phrase was translated successfull, then
  21. state is True but when phrase could not being found, state is False.
  22. Parameters
  23. ----------
  24. content : str
  25. Content of the translated phrase.
  26. success : bool, default: True
  27. State of the translation.
  28. """
  29. self.__success = success
  30. self.__content = content
  31. def __str__(self) -> str:
  32. """ This returns content of the phrase.
  33. Returns
  34. -------
  35. str
  36. Content of the translated phrase.
  37. """
  38. return self.__content
  39. @property
  40. def text(self) -> str:
  41. """ String content of the phrase.
  42. Returns
  43. -------
  44. str
  45. Content of the translated phrase.
  46. """
  47. return self.__content
  48. @property
  49. def valid(self) -> bool:
  50. """ This returns that phrase was translated propertly.
  51. Returns
  52. -------
  53. bool
  54. True when phrase was translated propertly or false when not.
  55. """
  56. return self.__success
  57. def format(self, params: dict) -> str:
  58. """ This format translated phrase by inserting given items into it.
  59. Parameters
  60. ----------
  61. params : str
  62. Items to insert into translated string.
  63. Returns
  64. -------
  65. str
  66. Translated content with inserted given values.
  67. """
  68. if not self.__success:
  69. return self.__content
  70. parts = self.__content.split("#{")
  71. results = parts.pop(0)
  72. for count in parts:
  73. elements = count.split("}")
  74. if len(elements) == 1:
  75. results = results + count
  76. continue
  77. name = elements.pop(0).strip()
  78. rest = str("}").join(elements)
  79. if not name in params:
  80. results = results + rest
  81. continue
  82. results = results + str(params[name]) + rest
  83. return results