Trolltech Home | Qt-interest Home | Recent Threads | All Threads | Author | Date
All threads index page 5

Qt-interest Archive, July 2007
(localization) Help transforming gettext po files to ts files


Message 1 in thread

There is a python project that help with that (and probably the ubuntu
launchpad localization toolkit) but I did not manage to make it work.
Hope it can helps some people. If you are moving from a project that
uses gettext po file for localization to Qt that might be handy. The
po files have to be slightly pre-processed, and there might corner
case where it fails (read the comments).

Regards,
Benjamin.

[bsergean@marge1 i18n]$ cat po2ts.py
#!/usr/bin/env python
"""
Update Qt ts translation files from special(*) gettext po files translations

(*)
 - The po files must be utf-8 encoded
 - The po files must not contains multilines strings
"""

# Written by Benjamin Sergeant <bsergean@xxxxxxxxx>
__revision__ = '$Id: po2ts.py 182 2007-06-19 22:52:04Z bsergean $'

from sys import argv
from xml.dom.minidom import parse

# Original content
def messagesFromPoFile(poFile):
    lines = open(poFile).readlines()

    cleanedLines = []
    for l in lines:
        if not l.startswith('#') and not l == '\n' :
            cleanedLines.append(l)

    def pairwise(iterable):
        it = iter(iterable)
        while True:
            yield it.next(), it.next()

    def cleanMsg(msg, id):
        '''
        input: $msg "Transparent"\n
        output: Transparent
        '''
        msg = msg[len(id)+1:]
        msg = msg[1:-2]
        return msg

    messages = {}
    for msgid, msgstr in pairwise(cleanedLines):
        id = cleanMsg(msgid, 'msgid')
        translation = cleanMsg(msgstr, 'msgstr')
        messages[id] = translation

    return messages

def updateTs(tsFile, messages):
    ''' See http://mail.python.org/pipermail/xml-sig/2004-August/010414.html
for the unicode black magic '''
    doc = parse(tsFile)

    msgNodes = doc.getElementsByTagName('message')
    for e in msgNodes:
        for msgNode in e.childNodes:
            if msgNode.localName == 'source':
                source = msgNode.childNodes[0].data

            if msgNode.localName == 'translation':
                if source in messages:
                    translation = messages[source].decode('utf-8')
                    if not msgNode.hasChildNodes():
                        text = doc.createTextNode(translation)
                        msgNode.appendChild(text)
                    else:
                        msgNode.childNodes[0].data = translation

    f = open(tsFile, 'w')
    f.write(doc.toxml('utf-8'))
    f.close()

    # clean-up
    doc.unlink()

# First parameter is the po file
# Second parameter is the ts file
updateTs(argv[2], messagesFromPoFile(argv[1]))

--
 [ signature omitted ]