Please nominate your Qt Champions for 2021!

Flat to contextual translations

  • Hi there, and thx for reading this post.

    Most internationalized apps use a "flat" (no context) translation
    system, e.g. gettext, wheras qt uses a contextual translation engine.

    That's why I wrote flat2ct, a perl script that merges both an existing
    flat file and a fresh empty .ts file.


    lconvert myapp.po -o flat.ts

    lupdate src/* -ts empty.ts

    flat2ct flat.ts empty.ts > myapp.ts

    et voilĂ ...


    Copyright (C) 2014 by Christophe Gros

    This program is free software; you can redistribute it and/or modify

    it under the terms of the GNU General Public License as published by

    the Free Software Foundation; either version 2 of the License, or

    (at your option) any later version.

    This program is distributed in the hope that it will be useful,

    but WITHOUT ANY WARRANTY; without even the implied warranty of


    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License

    along with this program; if not, write to the

    Free Software Foundation, Inc.,

    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA

    This script converts "flat" i.e. contextless .ts files produced by lconvert from .po files into contextual ts files

    use XML::XPath;
    use XML::XPath::XMLParser;
    use Encode;

    die("usage: flat2ct flat.ts contextual.ts") if($ARGV[0] eq "" || $ARGV[1] eq "");
    my %tbl;
    my $xp = XML::XPath->new(filename => $ARGV[0]);
    my $nodeset = $xp->find('/TS/context/message');
    my $s;
    foreach my $node ($nodeset->get_nodelist) {
    my @l = $node->getChildNodes();
    foreach $j (@l) {
    if($j->getName() eq "source") { $s = $$j->[4]->[0]->getData(); }
    if($j->getName() eq "translation") { $tbl{$s} = defined($$j->[4]->[0]) ? $$j->[4]->[0]->getData() : "" }

    $xp = XML::XPath->new(filename => $ARGV[1]);
    $nodeset = $xp->find('/TS/context/message');

    foreach my $node ($nodeset->get_nodelist) {
    my @l = $node->getChildNodes();
    foreach $j (@l) {
    #$s = "";
    if($j->getName() eq "source") { $s = $$j->[4]->[0]->getData; } #{ my $t = $$j->[4]->[0]; $$t->[3] = "xyz"; }
    if($j->getName() eq "translation") { $j->removeAttribute("type"); $$j->[4]->[0] = new XML::XPath::Node::Text; $$j->[4]->[0]->appendText(encode("utf-8", $tbl{$s})); }

    $nodeset = $xp->find('/');
    print "<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE TS>";
    foreach my $node ($nodeset->get_nodelist)
    { print XML::XPath::XMLParser::as_string($node) . "\n";}@

Log in to reply