Package translate :: Package convert :: Module po2txt

[hide private]
[frames] | no frames]

# Source Code for Module translate.convert.po2txt

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2004-2006 Zuza Software Foundation
      5  #
      6  # This file is part of translate.
      7  #
      8  # translate is free software; you can redistribute it and/or modify
      9  # it under the terms of the GNU General Public License as published by
     10  # the Free Software Foundation; either version 2 of the License, or
     11  # (at your option) any later version.
     12  #
     13  # translate is distributed in the hope that it will be useful,
     14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  # GNU General Public License for more details.
     17  #
     18  # You should have received a copy of the GNU General Public License
     19  # along with translate; if not, write to the Free Software
     20  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     21  #
     22
     23  """convert Gettext PO localization files to plain text (.txt) files
     24
     25  see: http://translate.sourceforge.net/wiki/toolkit/po2txt for examples and
     26  usage instructions
     27  """
     28
     29  from translate.storage import factory
     30  try:
     31      import textwrap
     32  except:
     33      textwrap = None
     34
     35 -class po2txt:
     36      """po2txt can take a po file and generate txt. best to give it a template file otherwise will just concat msgstrs"""
     37 -    def __init__(self, wrap=None):
     38          self.wrap = wrap
     39
     40 -    def wrapmessage(self, message):
     41          """rewraps text as required"""
     42          if self.wrap is None:
     43              return message
     44          return "\n".join([textwrap.fill(line, self.wrap, replace_whitespace=False) for line in message.split("\n")])
     45
     46 -    def convertstore(self, inputstore, includefuzzy):
     47          """converts a file to txt format"""
     48          txtresult = ""
     49          for unit in inputstore.units:
     50              if unit.isheader():
     51                  continue
     52              if unit.istranslated() or (includefuzzy and unit.isfuzzy()):
     53                  txtresult += self.wrapmessage(unit.target) + "\n" + "\n"
     54              else:
     55                  txtresult += self.wrapmessage(unit.source) + "\n" + "\n"
     56          return txtresult.rstrip()
     57
     58 -    def mergestore(self, inputstore, templatetext, includefuzzy):
     59          """converts a file to txt format"""
     60          txtresult = templatetext
     61          # TODO: make a list of blocks of text and translate them individually
     62          # rather than using replace
     63          for unit in inputstore.units:
     64              if unit.isheader():
     65                  continue
     66              if not unit.isfuzzy() or includefuzzy:
     67                  txtsource = unit.source
     68                  txttarget = self.wrapmessage(unit.target)
     69                  if unit.istranslated():
     70                      txtresult = txtresult.replace(txtsource, txttarget)
     71          return txtresult
     72
     73 -def converttxt(inputfile, outputfile, templatefile, wrap=None, includefuzzy=False, encoding='utf-8'):
     74      """reads in stdin using fromfileclass, converts using convertorclass, writes to stdout"""
     75      inputstore = factory.getobject(inputfile)
     76      convertor = po2txt(wrap=wrap)
     77      if templatefile is None:
     78          outputstring = convertor.convertstore(inputstore, includefuzzy)
     79      else:
     80          templatestring = templatefile.read().decode(encoding)
     81          outputstring = convertor.mergestore(inputstore, templatestring, includefuzzy)
     82      outputfile.write(outputstring.encode('utf-8'))
     83      return 1
     84
     85 -def main(argv=None):
     86      from translate.convert import convert
     87      from translate.misc import stdiotell
     88      import sys
     89      sys.stdout = stdiotell.StdIOWrapper(sys.stdout)
     90      formats = {("po", "txt"):("txt", converttxt), ("po"):("txt", converttxt), ("xlf", "txt"):("txt", converttxt), ("xlf"):("txt", converttxt)}
     91      parser = convert.ConvertOptionParser(formats, usetemplates=True, description=__doc__)
     92      parser.add_option("", "--encoding", dest="encoding", default='utf-8', type="string",
     93              help="The encoding of the template file (default: UTF-8)")
     94      parser.passthrough.append("encoding")
     95      if textwrap is not None:
     96          parser.add_option("-w", "--wrap", dest="wrap", default=None, type="int",
     97                  help="set number of columns to wrap text at", metavar="WRAP")
     98          parser.passthrough.append("wrap")
     99      parser.add_fuzzy_option()
    100      parser.run(argv)
    101
    102
    103  if __name__ == '__main__':
    104      main()
    105