繁体   English   中英

如何让python的argparse生成非英文文本?

[英]How to make python's argparse generate Non-English text?

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.py使用python3 Beispiel.py -h以下帮助输出:

Verwendung: Beispiel.py [-h] Eingabe

positional arguments:
  Eingabe

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

argparse使用 受 GNU gettext 启发gettext API 您可以使用此 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文档

我在argparse捷克语翻译的README.md中更详细地发布了这些说明。

一种方法,来自 Peter Otten 的这篇文章

我对 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..."))

您仍然必须自己提供所有翻译。

这是一个法语翻译的解决方案,其中创建一个转换字典,其中包含遇到的英语关键字的翻译

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

这是一个 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM