4

I would like to use googletrans to make use of the Google translate API. However, there are strings where are variable names in it:

User "%(first_name)s %(last_name)s (%(email)s)" has been deleted.

If I use this via googletrans I get

from googletrans import Translator
translator = Translator()
translator.translate(u'User "%(first_name)s %(last_name)s (%(email)s)" has been assigned.', src='en', dest='fr').text

I get the following:

L'utilisateur "% (first_name) s% (last_name) s (% (email) s)" a été affecté.

However, the "%(first_name) s% (last_name)s (%(email)s)" has some strings introduced. Is there a way around this? I've already tried:

u'User "<span class="notranslate">%(first_name)s %(last_name)s (%(email)s)</span>" has been assigned.'
Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
math
  • 1,868
  • 4
  • 26
  • 60
  • 1
    Can you describe the actual problem you are facing?It's somewhat hard for me to read and understand what your actual problem is. – Pavindu Feb 10 '19 at 15:47
  • @math, did my answer solve your issue? I could not find a documented way to exclude part of the text from translation (or being modified), but my answer should do the trick for your case unless I am missing something. – Ulrich Stern Feb 14 '19 at 21:48

2 Answers2

2

It seems Googletrans leaves, e.g., __1__ untouched. So you can replace %(first_name)s with __0__, %(last_name)s with __1__, etc. before you translate, and then restore the variables afterwards. Here code to do this:

from googletrans import Translator
import re

translator = Translator()
txtorig = u'User "%(first_name)s %(last_name)s (%(email)s)" has been assigned.'

# temporarily replace variables of format "%(example_name)s" with "__n__" to
#  protect them during translate()
VAR, REPL = re.compile(r'%\(\w+\)s'), re.compile(r'__(\d+)__')
varlist = []
def replace(matchobj):
  varlist.append(matchobj.group())
  return "__%d__" %(len(varlist)-1)
def restore(matchobj):
  return varlist[int(matchobj.group(1))]

txtorig = VAR.sub(replace, txtorig)
txttrans = translator.translate(txtorig, src='en', dest='fr').text
txttrans = REPL.sub(restore, txttrans)

print(txttrans)

Here the result:

L'utilisateur "%(first_name)s %(last_name)s (%(email)s)" a été attribué.
Ulrich Stern
  • 10,761
  • 5
  • 55
  • 76
  • Actually you need the following format: (3 before) string (2 after) ___%s__ I got a problem with the following translation: From Language code: 'en' To Language code: 'si' Content: "You gave __1__ to __2__" Result: ඔබ __2__ ට __2__ ලබා දුන්නා – Roger Gusmao Apr 10 '21 at 09:00
0

Actually, you need the following format:

(3 '_' before) (string) (2 '_' after)
Like: ___%s__
Roger Gusmao
  • 3,788
  • 1
  • 20
  • 17