Skip to content

Instantly share code, notes, and snippets.

@smola
Created September 17, 2013 21:18
Show Gist options
  • Save smola/6600778 to your computer and use it in GitHub Desktop.
Save smola/6600778 to your computer and use it in GitHub Desktop.
A Python script for swaping source and target language on a Gettext PO file.
#!/usr/bin/env python
# poswap.py
#
# Copyright (C) 2013 Santiago M. Mola
# Released under the terms of the MIT License.
#
"""
Swaps the source and target language in a Gettext PO file.
Learn more at http://mola.io/2013/09/17/swapping-languages-in-gettext-po-file
"""
import sys
try:
from translate.storage.pypo import pofile
except ImportError:
print 'This script requires Translate Toolkit.'
print 'Download it at http://toolkit.translatehouse.org/'
sys.exit(1)
if len(sys.argv) != 2:
print 'USAGE: %s <PO file>' % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
po = pofile(open(filename, 'r'))
# Swap every unit, except the first one,
# which should be the gettext header.
for i in po.units[1:]:
source = i.getsource()
target = i.gettarget()
i.setsource(target)
i.settarget(source)
print po
@egor83
Copy link

egor83 commented Jun 6, 2024

Thanks for your work!

An updated version of the script is as follows, to be run from Python console:

import sys

try:
  from translate.storage.pypo import pofile
except ImportError:
  print('This script requires Translate Toolkit.')
  print('Download it at http://toolkit.translatehouse.org/')
  sys.exit(1)

filename = "poswap.po"

po = pofile(open(filename, 'rb'))

# Swap every unit, except the first one,
# which should be the gettext header.
for i in po.units[1:]:
  source = i.getsource()
  target = i.gettarget()
  i.setsource(target)
  i.settarget(source)

po.savefile("output.po")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment