对于我的项目的本地化,我使用 gettext。我使用po2json脚本将我的翻译文件从.po格式转换为.json格式。除了一件事之外,一切都很好 - 如果我要转换的行包含控制字符,则在 .json 文件中这些字符被转义,最终字符串与代码不匹配(因此这个短语不翻译)。我试图理解脚本,但我不知道 Perl,也不理解额外斜杠的由来。
这是原始 .po 文件和转换后的 .json 的代码和部分:
剧本:
my $pos = Locale::PO->load_file_asarray($src) or die "Can't parse po file [$src].";
foreach my $po (@$pos)
{
my $qmsgid1 = $po->msgid;
my $msgid1 = $po->dequote( $qmsgid1 );
my $qmsgctxt = $po->msgctxt;
my $msgctxt = $po->dequote($qmsgctxt) if $qmsgctxt;
# build the new msgid key
my $msg_ctxt_id = defined($msgctxt) ? join($gettext_context_glue, ($msgctxt, $msgid1)) : $msgid1;
# build translation side
my @trans;
# msgid plural side
my $qmsgid_plural = $po->msgid_plural;
my $msgid2 = $po->dequote( $qmsgid_plural ) if $qmsgid_plural;
push(@trans, $msgid2);
# translated string
# this shows up different if we're plural
if (defined($msgid2) && length($msgid2))
{
my $plurals = $po->msgstr_n;
for (my $i=0; $i<$plural_form_count; $i++)
{
my $qstr = ref($plurals) ? $$plurals{$i} : undef;
my $str = $po->dequote( $qstr ) if $qstr;
push(@trans, $str);
}
# singular
} else {
my $qmsgstr = $po->msgstr;
my $msgstr = $po->dequote( $qmsgstr ) if $qmsgstr;
push(@trans, $msgstr);
}
$$json{$msg_ctxt_id} = \@trans;
}
my $jsonobj = new JSON;
my $basename = basename($src);
$basename =~ s/\.pot?$//;
if ($pretty)
{
print $jsonobj->pretty->encode( { $basename => $json });
} else {
print $jsonobj->encode( { $basename => $json } );
}
源 .po 文件示例:
#: some/path/to/file1.php:37
msgid "Original string without command character"
msgstr "Translated string without command character"
#: some/path/to/file2.php:73
msgid "Original string with\ncommand character"
msgstr "Translated string with\ncommand character"
转换后的 .json 文件:
{"Original string without command character":[null,"Original string without command character"],"Translated string with\\ncommand character":[null,"Translated string with\\ncommand character"]}
我将不胜感激任何建议或提示!
对不起,我真的不熟悉 Perl...