如何将带有 msgid 作为原始翻译字符串和 msgstr 作为翻译字符串的 po 翻译文件转换为 2 个不同的 json 文件(en 和 fr)

问题描述 投票:0回答:1

我有一个遵循以下格式的 .po 文件(保持精简 - 请注意,每组字符串中只有一个 msgid 和 mstr):

msgid "hello everyone"
msgstr "bonjour toute la monde"

msgid 是英文原文,msgstr 是法文翻译文本。 我们目前正在尝试使用库 i18next-gettext-converter,但不确定如何使用该库执行此类任务(如果可能的话),或者是否有其他 javascript 库可以满足我们的需求。

我们希望我们的一个大 .po 文件能够生成 1 个英语翻译和 1 个法语翻译文件,以便可以使用 react-i18next 库。

我尝试过将 cli 选项与 -l 和 -s 标志一起使用,并尝试使用 -K 选项标志,但似乎没有什么可以接近。

javascript reactjs typescript i18next react-i18next
1个回答
0
投票

我认为你应该读取 .po 文件并根据需要编写一个新文件,无需任何库,这里有一个片段供您开始:

// node format.js
const fs = require('fs');

function parsePoFile(poFilePath) {
    const content = fs.readFileSync(poFilePath, 'utf8');
    const entries = content.split('\n\n').map(entry => {
        const lines = entry.trim().split('\n');
        const msgid = lines.find(line => line.startsWith('msgid')).split('msgid ')[1];
        const msgstr = lines.find(line => line.startsWith('msgstr')).split('msgstr ')[1];
        return { msgid, msgstr };
    });
    return entries;
}

function generateTranslationFile(entries, lang) {
    const translations = entries.reduce((acc, entry) => {
        acc[entry.msgid] = entry.msgstr;
        return acc;
    }, {});

    fs.writeFileSync(`translations.${lang}.json`, JSON.stringify(translations, null, 2), 'utf8');
}

const poFilePath = 'your_po_file.po';
const entries = parsePoFile(poFilePath);
generateTranslationFile(entries, 'en'); // English translation file
generateTranslationFile(entries, 'fr'); // French translation file

© www.soinside.com 2019 - 2024. All rights reserved.