将生成的JavaScript文件中的”\n”替换为换行符。

huangapple go评论65阅读模式
英文:

Replace \n with newline in generated javascript file

问题

我正在尝试在React Native应用程序中实现本地化。为了节省时间,我尝试创建一个Python程序,使用OpenAI API来翻译应用程序的英文文本的JavaScript文件。

import os
import openai

def translate_text(text, language):
    """使用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():
    """将英文通用文件中的所有文本翻译成其他语言。"""
    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 {
    //Bottom Navigation
    homeNav: 'Inicio',
    infoNav: 'Información',
    supportNav: 'Soporte',
    profileNav: 'Perfil',
    //Sign Up Screen
    signUp: 'Registrarse',
    pleaseEnterStep1: 'Por favor ingrese su correo electrónico y contraseña para crear su cuenta',
    pleaseEnterStep2: 'Por favor ingrese su nombre, apellido y número de teléfono laboral',
    // 等等...
}

当我运行程序时,原始的英文文件被正确翻译,但是换行字符被添加,而不是移到下一行,这是期望的结果,整个文件都在一行上。我用'\n'替换为''以删除换行符,但是保持新生成的文件正确格式化的最佳方法是什么?

我还尝试将'\n'替换为回车符'\r\n',但我认为在这种情况下这不太合适,因为这不仅仅是一个文本文件。

英文:

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 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.

First time Stack Overflow entry here, so please let me know if I missed any info, thanks.

答案1

得分: -2

为了确保生成的文件格式正确,并且具有适当的换行符,您可以按照以下方式修改您的代码:

  1. 更新 translate_text 函数以删除翻译文本中的换行符:
translated_text = repr(completion.choices[0].message.content).strip('\n')
  1. 修改 main 函数以使用换行符转义序列 (\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)

这将用实际的换行字符 (\n) 替换翻译文本中的转义换行字符 (\\n),从而生成具有正确换行的格式的代码文件。
希望对您有所帮助!

英文:

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!

huangapple
  • 本文由 发表于 2023年6月22日 05:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定