我正在尝试在React Native应用程序中实现本地化。为了保存时间,我尝试创建一个python程序,使用OpenAI API从应用程序中翻译英语文本的JavaScript文件。
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()
翻译后的文件看起来像这样
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...
当我运行程序时,原始的英语文件被正确翻译,然而换行符被添加而不是移动到下一行,这是预期的结果,整个文件在一行上。我用''替换了''以删除换行符,但是确保新生成的文件格式正确的最佳方法是什么呢?
我还尝试用回车'\r\n'替换'\n',但我认为这在这种情况下不合适,因为这不应该只是一个文本文件。
第一次进入堆栈溢出这里,所以请让我知道,如果我错过了任何信息,谢谢。
1条答案
按热度按时间nfs0ujit1#
要确保生成的文件使用适当的换行符正确格式化,可以按如下所示修改代码:
1.更新translate_text函数以删除翻译文本中的换行符:
2.修改main函数,使用换行符
(\n)
编写带有适当换行符的翻译文本:这将用实际的换行符(
\n
)替换翻译文本中的转义换行符(\\n
),从而在生成的文件中生成具有换行符的正确格式的代码。希望能帮上忙!