我有一个遵循以下格式的 .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 选项标志,但似乎没有什么可以接近。
我认为你应该读取 .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