1
0

templatetranslator.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Template Translator v0.2
  4. # Regex-based automatic translator for common strings in gettext files.
  5. #
  6. # Copyright 2016-2017 roptat <julien@lepiller.eu>
  7. #
  8. # This program is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. import sys
  13. import re
  14. import polib
  15. import os.path
  16. class TemplateTranslator:
  17. def __init__(self, files):
  18. self.regexps = []
  19. self.files = files
  20. def append(self, regexp, translation):
  21. self.regexps.append([regexp, translation])
  22. def convert(self, entry, regexp, template):
  23. m = regexp.match(entry.msgid)
  24. # do not modify anything if the translation is already correct
  25. #if m and ("fuzzy" in entry.flags or not entry.msgstr):
  26. if m:
  27. msgstr = template
  28. try:
  29. msgstr = msgstr.replace("#1", m.group(1))
  30. msgstr = msgstr.replace('#2', m.group(2))
  31. msgstr = msgstr.replace('#3', m.group(3))
  32. msgstr = msgstr.replace('#4', m.group(4))
  33. msgstr = msgstr.replace('#5', m.group(5))
  34. except:
  35. x=1
  36. entry.msgstr = msgstr
  37. if "fuzzy" in entry.flags:
  38. entry.flags.remove("fuzzy")
  39. def translate_one(self, filename, language):
  40. realname = language + '/' + filename
  41. if not os.path.exists(realname):
  42. print(realname, 'does not exist.')
  43. return
  44. po = polib.pofile(realname)
  45. for entry in po:
  46. for reg in self.regexps:
  47. if language in reg[1]:
  48. self.convert(entry, reg[0], reg[1][language])
  49. po.save()
  50. def translate(self, languages):
  51. number = len(self.files)
  52. current = 1
  53. for filename in self.files:
  54. print('Traitement du fichier ', current, '/', number, ' \r',
  55. end="", flush=True),
  56. current = current + 1
  57. for language in languages:
  58. self.translate_one(filename, language)
  59. print('')