Translate using python except variables

Viewed 48

I am trying to translate Stellaris game files to turkish language using deep translate library.

toBeTranslated = "Scans indicate the presence of a foreign, alien-made object on one of §H[Root.GetName]'s§! many frozen mountain tops."

translated = GoogleTranslator(source='en', target='tr').translate(text=toBeTranslated)

Problem is that it is going to translate variables too. Variables are in this case what is between [ and ]. Other variables can be between § and §. So in this case I dont want string §H[Root.GetName]'s§ to be translated but everything else should be translated. How can I achieve this?

1 Answers

Try this approach:

  1. Create a regex expression to capture strings starting and ending with § or [], capture strings preceding § or [] and capture strings succeeding § or [].
  2. Translate the captured preceding and succeeding strings.
  3. Concatenate the translated and excluded strings.

See code below:

import re

regex_exp = r"([\s\S]*?)(\§.+\§|\[.+\])([\s\S]*?$)"
text = "Scans indicate the presence of a foreign, alien-made object on one of §H[Root.GetName]'s§! many frozen mountain tops."

result = re.search(regex_exp, text)

trans_group1 = GoogleTranslator(source='en', target='tr').translate(text=result.group(1))
trans_group3 = GoogleTranslator(source='en', target='tr').translate(text=result.group(3))

#result.group(2) is the excluded value

translated_text = trans_group1 + result.group(2) + trans_group3
Related