当前位置: 首页>>代码示例>>Python>>正文


Python pofile.write_po函数代码示例

本文整理汇总了Python中babel.messages.pofile.write_po函数的典型用法代码示例。如果您正苦于以下问题:Python write_po函数的具体用法?Python write_po怎么用?Python write_po使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了write_po函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

    def run(self):
        log.info('translating catalog %r based on %r', self.output_file,
                 self.input_file)

        infile = open(self.input_file, 'r')
        try:
            # Although reading from the catalog template, read_po must be fed
            # the locale in order to correcly calculate plurals
            catalog = read_po(infile, locale=self.locale)
        finally:
            infile.close()

        catalog.locale = self._locale
        catalog.fuzzy = False

        for message in catalog:
            if message.id:
                # Recopie de l'id du message dans la traduction.
                message.string = message.id
                catalog[message.id] = message

        outfile = open(self.output_file, 'w')
        try:
            write_po(outfile, catalog)
        finally:
            outfile.close()
开发者ID:vigilo,项目名称:common,代码行数:26,代码来源:commands.py

示例2: extract_messages

def extract_messages(dirs):
    catalog = Catalog(
        project='Open Library',
        copyright_holder='Internet Archive'
    )
    METHODS = [
        ("**.py", "python"),
        ("**.html", "openlibrary.i18n:extract_templetor")
    ]
    COMMENT_TAGS = ["NOTE:"]

    for d in dirs:
        if '.html' in d:
            extracted = [(d,) + extract for extract in extract_from_file("openlibrary.i18n:extract_templetor", d)]
        else:
            extracted = extract_from_dir(d, METHODS, comment_tags=COMMENT_TAGS, strip_comment_tags=True)
        for filename, lineno, message, comments, context in extracted:
            catalog.add(message, None, [(filename, lineno)], auto_comments=comments)

    path = os.path.join(root, 'messages.pot')
    f = open(path, 'w')
    write_po(f, catalog)
    f.close()

    print('wrote template to', path)
开发者ID:hornc,项目名称:openlibrary-1,代码行数:25,代码来源:__init__.py

示例3: save

 def save(self, ignore_obsolete=True, include_previous=True, width=80):
   if not self.pod.file_exists(self.pod_path):
     self.pod.create_file(self.pod_path, None)
   outfile = self.pod.open_file(self.pod_path, mode='w')
   pofile.write_po(outfile, self, ignore_obsolete=ignore_obsolete,
                   include_previous=include_previous, width=width)
   outfile.close()
开发者ID:zen-johnttan,项目名称:pygrow,代码行数:7,代码来源:catalogs.py

示例4: handle

    def handle(self, *args, **options):
        if args:
            # mimics puente.management.commands.extract for a list of files
            outputdir = os.path.join(settings.ROOT, 'locale', 'templates',
                                     'LC_MESSAGES')
            if not os.path.isdir(outputdir):
                os.makedirs(outputdir)

            catalog = Catalog(
                header_comment='',
                project=get_setting('PROJECT'),
                version=get_setting('VERSION'),
                msgid_bugs_address=get_setting('MSGID_BUGS_ADDRESS'),
                charset='utf-8',
            )

            for filename, lineno, msg, cmts, ctxt in extract_from_files(args):
                catalog.add(msg, None, [(filename, lineno)], auto_comments=cmts,
                            context=ctxt)

            with open(os.path.join(outputdir, '%s.pot' % DOMAIN), 'wb') as fp:
                write_po(fp, catalog, width=80)
        else:
            # This is basically a wrapper around the puente extract
            # command, we might want to do some things around this in the
            # future
            gettext_extract()
        pot_to_langfiles(DOMAIN)
开发者ID:Delphine,项目名称:bedrock,代码行数:28,代码来源:l10n_extract.py

示例5: import_csv_file

 def import_csv_file(self, path):
     """Imports a CSV file formatted with locales in the header row and
     translations in the body rows."""
     default_locale = self.pod.podspec.localization.get('default_locale', 'en')
     locales_to_catalogs = {}
     with open(path) as fp:
         reader = csv.DictReader(fp)
         for row in reader:
             if default_locale not in row:
                 text = 'Locale {} not found in {}'.format(default_locale, path)
                 raise Error(text)
             msgid = row[default_locale]
             msgid = msgid.decode('utf-8')
             for locale, translation in row.iteritems():
                 if locale == default_locale:
                     continue
                 translation = translation.decode('utf-8')
                 message = catalog.Message(msgid, translation)
                 if locale not in locales_to_catalogs:
                     locales_to_catalogs[locale] = catalog.Catalog()
                 locales_to_catalogs[locale][msgid] = message
     for locale, catalog_obj in locales_to_catalogs.iteritems():
         fp = cStringIO.StringIO()
         pofile.write_po(fp, catalog_obj)
         fp.seek(0)
         content = fp.read()
         self.import_content(locale, content)
         fp.close()
开发者ID:grow,项目名称:grow,代码行数:28,代码来源:importers.py

示例6: machine_translate

    def machine_translate(self):
        locale = str(self.locale)
        domain = 'messages'
        infile = self.pod.open_file(self.pod_path, 'U')
        try:
            babel_catalog = pofile.read_po(infile, locale=locale, domain=domain)
        finally:
            infile.close()

        # Get strings to translate.
        # TODO(jeremydw): Use actual string, not the msgid. Currently we assume
        # the msgid is the source string.
        messages_to_translate = [message for message in babel_catalog
                                 if not message.string]
        strings_to_translate = [message.id for message in messages_to_translate]
        if not strings_to_translate:
            logging.info('No untranslated strings for {}, skipping.'.format(locale))
            return

        # Convert Python-format named placeholders to numerical placeholders
        # compatible with Google Translate. Ex: %(name)s => (O).
        placeholders = []  # Lists (#) placeholders to %(name)s placeholders.
        for n, string in enumerate(strings_to_translate):
            match = re.search('(%\([^\)]*\)\w)', string)
            if not match:
                placeholders.append(None)
                continue
            for i, group in enumerate(match.groups()):
                num_placeholder = '({})'.format(i)
                nums_to_names = {}
                nums_to_names[num_placeholder] = group
                replaced_string = string.replace(group, num_placeholder)
                placeholders.append(nums_to_names)
                strings_to_translate[n] = replaced_string

        machine_translator = goslate.Goslate()
        results = machine_translator.translate(strings_to_translate, locale)

        for i, string in enumerate(results):
            message = messages_to_translate[i]

            # Replace numerical placeholders with named placeholders.
            if placeholders[i]:
                for num_placeholder, name_placeholder in placeholders[i].iteritems():
                    string = string.replace(num_placeholder, name_placeholder)

            message.string = string
            if isinstance(string, unicode):
                string = string.encode('utf-8')
            source = message.id
            source = (source.encode('utf-8')
                      if isinstance(source, unicode) else source)

        outfile = self.pod.open_file(self.pod_path, mode='w')
        try:
            pofile.write_po(outfile, babel_catalog, width=80)
        finally:
            outfile.close()
        text = 'Machine translated {} strings: {}'
        logging.info(text.format(len(strings_to_translate), self.pod_path))
开发者ID:hookerz,项目名称:grow,代码行数:60,代码来源:catalogs.py

示例7: init_catalog

  def init_catalog(self):
    locale = str(self.locale)
    input_path = os.path.join('translations', 'messages.pot')
    output_path = os.path.join('translations', locale, 'LC_MESSAGES', 'messages.po')
    logging.info('Creating catalog %r based on %r', output_path, input_path)
    infile = self.pod.open_file(input_path)
    try:
      babel_catalog = pofile.read_po(infile, locale=locale)
    finally:
      infile.close()

    babel_locale = babel.Locale.parse(locale)
    babel_catalog.locale = babel_locale
    babel_catalog.revision_date = datetime.now(util.LOCALTZ)
    babel_catalog.fuzzy = False

    # TODO(jeremydw): Optimize.
    # Creates directory if it doesn't exist.
    path = os.path.join(output_path)
    if not self.pod.file_exists(path):
      self.pod.create_file(path, None)

    outfile = self.pod.open_file(output_path, mode='w')
    try:
      pofile.write_po(outfile, babel_catalog, width=80)
    finally:
      outfile.close()
开发者ID:jbruwer,项目名称:pygrow,代码行数:27,代码来源:translations.py

示例8: write_clean_po

def write_clean_po(filename, catalog):
    """Writes out a .po file in a canonical way, to minimize spurious diffs."""
    catalog.creation_date = datetime.datetime(2000, 1, 1, 0, 0, 0)
    file = open(filename, 'w')
    pofile.write_po(file, catalog,
                    no_location=True, sort_output=True, ignore_obsolete=True)
    file.close()
开发者ID:santoshsahoo,项目名称:personfinder,代码行数:7,代码来源:update_messages.py

示例9: extract

  def extract(self):
    catalog_obj = catalog.Catalog()
    path = os.path.join(self.root, 'messages.pot')
    template = self.pod.open_file(path, mode='w')
    extracted = []

    # Extracts messages from views.
    pod_files = self.pod.list_dir('/')
    for pod_path in pod_files:
      if os.path.splitext(pod_path)[-1] in _TRANSLATABLE_EXTENSIONS:
        content = self.pod.read_file(pod_path)
        import cStringIO
        fp = cStringIO.StringIO()
        fp.write(content)
        fp.seek(0)
        import tokenize
        try:
          messages = extract.extract('python', fp)
          for message in messages:
            lineno, string, comments, context = message
            catalog_obj.add(string, None, [(pod_path, lineno)], auto_comments=comments, context=context)
        except tokenize.TokenError:
          print 'Problem extracting: {}'.format(pod_path)
          raise

    # TODO(jeremydw): Extract messages from content.

    # Writes to PO template.
    pofile.write_po(template, catalog_obj, width=80, no_location=True, omit_header=True, sort_output=True, sort_by_file=True)
    logging.info('Extracted {} messages from {} files to: {}'.format(len(extracted), len(pod_files), template))
    template.close()
    return catalog_obj
开发者ID:statusz,项目名称:pygrow,代码行数:32,代码来源:translations.py

示例10: test_with_context

    def test_with_context(self):
        buf = StringIO(
            r"""# Some string in the menu
#: main.py:1
msgctxt "Menu"
msgid "foo"
msgstr "Voh"

# Another string in the menu
#: main.py:2
msgctxt "Menu"
msgid "bar"
msgstr "Bahr"
"""
        )
        catalog = pofile.read_po(buf, ignore_obsolete=True)
        self.assertEqual(2, len(catalog))
        message = catalog.get("foo", context="Menu")
        self.assertEqual("Menu", message.context)
        message = catalog.get("bar", context="Menu")
        self.assertEqual("Menu", message.context)

        # And verify it pass through write_po
        out_buf = BytesIO()
        pofile.write_po(out_buf, catalog, omit_header=True)
        assert out_buf.getvalue().strip() == buf.getvalue().strip().encode("latin-1"), out_buf.getvalue()
开发者ID:vsajip,项目名称:babel3,代码行数:26,代码来源:pofile.py

示例11: upodate_component_xl_content2pofile

def upodate_component_xl_content2pofile(component_xl_file):
    component_dir = os.path.dirname(component_xl_file)

    # TODO: delete all po files.
    po_dict = {}

    src_wb = load_workbook(component_xl_file, use_iterators=True)
    src_ws = src_wb.get_sheet_by_name(name='Sheet')

    for row in src_ws.iter_rows():
        pofilename = row[0].internal_value
        if not po_dict.has_key(pofilename):
            po_dict[pofilename] = []

        values = []
        for cell in row[1:]:
            values.append(cell.internal_value)

        po_dict[pofilename].append(values)

    for pofilename in po_dict.keys():
        pofilepath = os.path.join(component_dir, pofilename)
        contents = po_dict[pofilename]
        catalog = convert_xlsm_content(contents)

        with open(pofilepath, 'w') as f:
            pofile.write_po(f, catalog)
开发者ID:huzhennan,项目名称:androidstring2xl,代码行数:27,代码来源:xlutils.py

示例12: test_unknown_language_write

def test_unknown_language_write():
    catalog = Catalog(locale='sr_SP')
    assert catalog.locale_identifier == 'sr_SP'
    assert not catalog.locale
    buf = BytesIO()
    pofile.write_po(buf, catalog)
    assert 'sr_SP' in buf.getvalue().decode()
开发者ID:Changaco,项目名称:babel,代码行数:7,代码来源:test_pofile.py

示例13: import_file

 def import_file(self, locale, po_path):
   if locale is None:
     raise Error('Must specify locale.')
   if not os.path.exists(po_path):
     raise Error('Couldn\'t find PO file: {}'.format(po_path))
   babel_locale = external_to_babel_locales.get(locale, locale)
   pod_translations_dir = os.path.join(
       'translations', babel_locale, 'LC_MESSAGES')
   pod_po_path = os.path.join(pod_translations_dir, 'messages.po')
   if self.pod.file_exists(pod_po_path):
     existing_po_file = self.pod.open_file(pod_po_path)
     existing_catalog = pofile.read_po(existing_po_file, babel_locale)
     po_file_to_merge = open(po_path)
     catalog_to_merge = pofile.read_po(po_file_to_merge, babel_locale)
     for message in catalog_to_merge:
       if message.id not in existing_catalog:
         existing_catalog[message.id] = message
       else:
         existing_catalog[message.id].string = message.string
     existing_po_file = self.pod.open_file(pod_po_path, mode='w')
     pofile.write_po(existing_po_file, existing_catalog, width=80,
                     omit_header=True, sort_output=True, sort_by_file=True)
     text = 'Imported {} translations: {}'
     self.pod.logger.info(text.format(len(catalog_to_merge), babel_locale))
   else:
     abs_po_path = self.pod.abs_path(pod_po_path)
     abs_po_dir = os.path.dirname(abs_po_path)
     _mkdir(abs_po_dir)
     shutil.copyfile(po_path, abs_po_path)
     self.pod.logger.info('Imported new catalog: {}'.format(babel_locale))
开发者ID:codedcolors,项目名称:pygrow,代码行数:30,代码来源:importers.py

示例14: merge

def merge(source, target_filename):
    """Merges the messages from the source Catalog into a .po file at
    target_filename.  Creates the target file if it doesn't exist."""
    if os.path.exists(target_filename):
        target = pofile.read_po(open(target_filename))
        for message in source:
            if message.id and message.string and not message.fuzzy:
                log_change(message.id in target and target[message.id], message)

                # This doesn't actually replace the message!  It just updates
                # the fields other than the string.  See Catalog.__setitem__.
                target[message.id] = message

                # We have to mutate the message to update the string and flags.
                target[message.id].string = message.string
                target[message.id].flags = message.flags
    else:
        for message in source:
            log_change(None, message)
        target = source

    target_file = create_file(target_filename)
    pofile.write_po(target_file, target,
                    no_location=True, sort_output=True, ignore_obsolete=True)
    target_file.close()
开发者ID:Aloknayan,项目名称:personfinder,代码行数:25,代码来源:merge_messages.py

示例15: test_update

    def test_update(self):
        template = Catalog()
        template.add("1")
        template.add("2")
        template.add("3")
        tmpl_file = os.path.join(self._i18n_dir(), 'temp-template.pot')
        with open(tmpl_file, "wb") as outfp:
            write_po(outfp, template)
        po_file = os.path.join(self._i18n_dir(), 'temp1.po')
        self.cli.run(sys.argv + ['init',
                                 '-l', 'fi',
                                 '-o', po_file,
                                 '-i', tmpl_file
                                 ])
        with open(po_file, "r") as infp:
            catalog = read_po(infp)
            assert len(catalog) == 3

        # Add another entry to the template

        template.add("4")

        with open(tmpl_file, "wb") as outfp:
            write_po(outfp, template)

        self.cli.run(sys.argv + ['update',
                                 '-l', 'fi_FI',
                                 '-o', po_file,
                                 '-i', tmpl_file])

        with open(po_file, "r") as infp:
            catalog = read_po(infp)
            assert len(catalog) == 4  # Catalog was updated
开发者ID:Mabusto,项目名称:babel,代码行数:33,代码来源:test_frontend.py


注:本文中的babel.messages.pofile.write_po函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。