【问题标题】:How to make python's argparse generate Non-English text?如何让python的argparse生成非英文文本?
【发布时间】:2014-05-21 23:59:22
【问题描述】:

argparse 模块“自动生成帮助和使用信息”。我可以为论点提供非英文名称并提供非英文帮助文本;但是帮助输出会变成至少两种语言的混合体,因为像 usagepositional argumentsoptional argumentsshow this help message and exit 这样的术语会自动生成为英文。

如何用翻译替换这个英文输出?

最好我想在脚本中提供翻译,这样脚本无论从哪里开始都会生成相同的输出。

编辑:根据 Jon-Eric 的回答,这里是他的解决方案示例:

import gettext

def Übersetzung(Text):
    Text = Text.replace("usage", "Verwendung")
    Text = Text.replace("show this help message and exit",
                        "zeige diese Hilfe an und tue nichts weiteres")
    Text = Text.replace("error:", "Fehler:")
    Text = Text.replace("the following arguments are required:",
                        "Die folgenden Argumente müssen angegeben werden:")
    return Text
gettext.gettext = Übersetzung

import argparse

Parser = argparse.ArgumentParser()
Parser.add_argument("Eingabe")
Argumente = Parser.parse_args()

print(Argumente.Eingabe)

保存为Beispiel.pypython3 Beispiel.py -h 一起提供以下帮助输出:

Verwendung: Beispiel.py [-h] Eingabe

positional arguments:
  Eingabe

optional arguments:
  -h, --help  zeige diese Hilfe an und tue nichts weiteres

【问题讨论】:

  • 请显示示例和代码。
  • 如果您想更改positional argumentsoptional arguments 的名称,您可以定义自己的argument_groups
  • @hpaulj:谢谢你的建议。 Jon-Eric 的 gettext.gettext 解决方案也适用于这些名称;我只是没有在上面的例子中替换它们。

标签: python internationalization argparse


【解决方案1】:

argparse 使用gettext API inspired by GNU gettext。 您可以使用此 API 以相对干净的方式集成您对argparse 的翻译。

为此,请在argparse 输出任何文本之前调用以下代码(但可能在import argparse 之后):

import gettext

# Use values that suit your project instead of 'argparse' and 'path/to/locale'
gettext.bindtextdomain('argparse', 'path/to/locale')
gettext.textdomain('argparse')

为了使该解决方案起作用,您的argparse 翻译必须位于path/to/locale/ll/LC_MESSAGES/argparse.mo,其中ll 是当前语言的代码(例如de;例如可以通过设置环境变量LANGUAGE)。

如何生成.mo 文件?

  1. pygettext --default-domain=argparse /usr/local/lib/python3.5/argparse.py
    • 使用argparse.py的实际位置
    • 创建文件argparse.pot
  2. cp argparse.pot argparse-ll.po
    • 使用实际语言代码代替ll
  3. 填写argparse-ll.po中缺少的翻译字符串
  4. msgfmt argparse-ll.po -o locale/ll/LC_MESSAGES/argparse.mo

有关创建.mo 文件的详细信息,请参阅gettext documentation

我已在我的Czech translation of argparseREADME.md 中更详细地发布了这些说明。

【讨论】:

    【解决方案2】:

    一种方式,来自 Peter Otten 的 this post

    我对 gettext 了解不多,但以下建议大多数 argparse 中的字符串已正确包装:

    $ cat localize_argparse.py
    
    import gettext
    
    def my_gettext(s):
        return s.upper()
    gettext.gettext = my_gettext
    
    import argparse
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("-V", action="version")
        args = parser.parse_args()
    
    $ python localize_argparse.py -h USAGE: localize_argparse.py [-h] [-V]
    
    OPTIONAL ARGUMENTS:   -h, --help  SHOW THIS HELP MESSAGE AND EXIT   -V
    show program's version number and exit
    

    “-V”选项的解决方法是添加帮助消息 明确的

    parser.add_argument("-V", ..., help=_("show..."))
    

    您仍然需要自己提供所有翻译。

    【讨论】:

    • 谢谢!这样做。只有在重新定义 gettext.gettext 之后才导入 argparse 似乎很重要。
    【解决方案3】:

    这是一个带有法语翻译的解决方案,其中创建一个转换字典来保存遇到的英语关键字的翻译

    def convertArgparseMessages(s):
        subDict = \
        {'positional arguments':'Arguments positionnels',
        'optional arguments':'Arguments optionnels',
        'show this help message and exit':'Affiche ce message et quitte'}
        if s in subDict:
            s = subDict[s]
        return s
    gettext.gettext = convertArgparseMessages
    import argparse
    

    【讨论】:

      【解决方案4】:

      这是一个 Python 模块,用于翻译 argparse 发出的所有消息。它旨在快速而肮脏地翻译成另一种语言(在我的情况下是法语,但可以根据您自己的语言随意调整)。如需更工业化的多语言方法,请查看出色的 Filip Bartek 解决方案。

      """
      This module is like argparse but in french. 
      Import it and use it like you would use argparse.
      
      DIRECTIVES:
      First copy-paste this code in a separate new file named french_argparse.py
      Put this new file beside your main.py file in the same top project folder.
      Then in the main.py file, import it like this:
      
      >>> import french_argparse as argparse
      """
      
      import gettext
      
      #################################################################################################################
      # The following translations are in French, but feel free to replace them with your own
      # Many messages are even not translated, because they seems to be more intended for the programmer than the user.
      # Phrases were extracted from the code at (https://github.com/python/cpython/blob/master/Lib/argparse.py)
      # On October 2019
      #################################################################################################################
      
      __TRANSLATIONS = {
          'ambiguous option: %(option)s could match %(matches)s': 'option ambiguë: %(option)s parmi %(matches)s',
          'argument "-" with mode %r': 'argument "-" en mode %r',
          'cannot merge actions - two groups are named %r': 'cannot merge actions - two groups are named %r',
          "can't open '%(filename)s': %(error)s": "can't open '%(filename)s': %(error)s",
          'dest= is required for options like %r': 'dest= is required for options like %r',
          'expected at least one argument': 'au moins un argument est attendu',
          'expected at most one argument': 'au plus un argument est attendu',
          'expected one argument': 'un argument est nécessaire',
          'ignored explicit argument %r': 'ignored explicit argument %r',
          'invalid choice: %(value)r (choose from %(choices)s)': 'choix invalide: %(value)r (parmi %(choices)s)',
          'invalid conflict_resolution value: %r': 'invalid conflict_resolution value: %r',
          'invalid option string %(option)r: must start with a character %(prefix_chars)r':
              'invalid option string %(option)r: must start with a character %(prefix_chars)r',
          'invalid %(type)s value: %(value)r': 'valeur invalide de type %(type)s: %(value)r',
          'mutually exclusive arguments must be optional': 'mutually exclusive arguments must be optional',
          'not allowed with argument %s': "pas permis avec l'argument %s",
          'one of the arguments %s is required': 'au moins un argument requis parmi %s',
          'optional arguments': 'arguments optionnels',
          'positional arguments': 'arguments positionnels',
          "'required' is an invalid argument for positionals": "'required' is an invalid argument for positionals",
          'show this help message and exit': 'afficher ce message et quitter',
          'unrecognized arguments: %s': 'argument non reconnu: %s',
          'unknown parser %(parser_name)r (choices: %(choices)s)': 'unknown parser %(parser_name)r (choices: %(choices)s)',
          'usage: ': 'usage: ',
          '%(prog)s: error: %(message)s\n': '%(prog)s: erreur: %(message)s\n',
          '%r is not callable': '%r is not callable',
      }
      
      
      gettext.gettext = lambda text: __TRANSLATIONS[text] or text
      
      ##############################################################################
      # Now import all argparse functionalities inside this module.
      #
      #   NB Many linters don't like the following line of code so we have disabled
      #   warnings for pylint, flake8 and PyCharm
      ##############################################################################
      
      # pylint: disable=all
      # noinspection PyUnresolvedReferences
      from argparse import *                  # noqa
      
      

      【讨论】:

        【解决方案5】:

        我遇到了类似的问题。 几乎所有消息都会按照帖子 5 中的说明进行正确翻译,但使用 parser.add_argument() 添加的帮助消息不会。 您可以通过对 argparse 使用非基于类的 gettext 和对应用程序使用基于类的 gettext 来解决问题。 看看https://github.com/jmo3300/py01_i18n_01中的app3.py

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-27
          • 2021-10-05
          • 2016-12-27
          • 1970-01-01
          • 1970-01-01
          • 2015-10-01
          • 1970-01-01
          • 2016-11-07
          相关资源
          最近更新 更多