Issue
I am trying to implement localization in a React Native application. To save time I tried to create a Python program to translate a JavaScript file of the English text from the app, using the OpenAI API.
import os
import openai
def translate_text(text, language):
"""Translates text from English to the specified language using ChatGPT."""
openai.api_key = os.getenv('OPENAI_API_KEY')
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": f"Translate only the text inside quotes (inside '', nothing else) in {text} to {language}, with cs being Czech, de being German, es being Spanish, fr being French, it being italian, ko being Korean, nl being Dutch, pl being Polish, and tr being Turkish. Do not include the newline character when there is a new line. This new file will be a typescript file, not just a text file. Ignore // comments"}
]
)
return repr(completion.choices[0].message.content).strip('"')
"""def main():
file = os.path.join("translations", "fr", "common.tsx")
with open(file, "r") as f:
text = f.read()
with open(os.path.join("translations", "fr", "common.tsx"), "w", encoding="utf-8") as f:
f.write(text.replace('\n', ''))"""
def main():
"""Translates all the texts in the English common file to other languages."""
english_file = os.path.join("translations", "en", "common.tsx")
with open(english_file, "r") as f:
english_text = (f.read()).replace('\n', '')
for language in ["cs", "de", "es", "fr", "it", "ko", "nl", "pl", "tr"]:
translated_text = translate_text(english_text, language)
with open(os.path.join("translations", language, "common.tsx"), "w", encoding="utf-8", newline='') as f:
f.write(translated_text)
if __name__ == "__main__":
main()
The translated file comes out looking like this
export default {\n //Bottom Navigation\n homeNav: 'Inicio',\n infoNav: 'Información',\n supportNav: 'Soporte',\n profileNav: 'Perfil',\n //Sign Up Screen\n signUp: 'Registrarse',\n pleaseEnterStep1: 'Por favor ingrese su correo electrónico y contraseña para crear su cuenta',\n pleaseEnterStep2: 'Por favor ingrese su nombre, apellido y número de teléfono laboral',\n etc...
When I run the program, the original English file is translated correctly, however the newline character was added instead of moving to the next line, which is the expected result, and the whole file is on one line. I replaced '' with '' to remove the newlines, but what is the best way to ensure the new generated file is correctly formatted.
I also tried replacing '\n' with the carriage return '\r\n', but I don't think that's appropriate in this situation because this isn't supposed to be just a text file.
Solution
To ensure the generated file is correctly formatted with appropriate line breaks, you can modify your code as follows:
1.Update the translate_text function to remove the line breaks from the translated text:
translated_text = repr(completion.choices[0].message.content).strip('"\n')
2.Modify the main function to write the translated text with proper line breaks using the newline escape sequence (\n)
:
translated_text = translate_text(english_text, language)
translated_text = translated_text.replace('\\n', '\n')
with open(os.path.join("translations", language, "common.tsx"), "w", encoding="utf-8") as f:
f.write(translated_text)
This will replace the escaped newline character (\\n
) in the translated text with an actual newline character (\n
), resulting in correctly formatted code with line breaks in the generated file.
Hope it helps!
Answered By - Chloe Harper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.