def example_i18n_pluralization():
    i18n.add_translation(
        'unread_number', {
            'zero': 'You do not have any unread mail.',
            'one': 'You have a new unread mail.',
            'few': 'You only have %{count} unread mails.',
            'many': 'You have %{count} unread mails.'
        })
    print(
        f"""{i18n.t('unread_number', count=0)}  # You do not have any unread mail.
{i18n.t('unread_number', count=1)}  # You have a new unread mail.
{i18n.t('unread_number', count=2)}  # You only have 2 unread mails.
{i18n.t('unread_number', count=15)}  # You have 15 unread mails.""")
def t(language, translation):
    """
    Translates RST strings to Regional Strings using i18n as a cache as parsing RST delays load by a lot to retrieve simple things that are used many times
    """
    i18n.set('locale', language)
    if translation == i18n.t(translation):
        rst = RstFile(download.download_cdragon_rstfile(language))
        try:
            name = rst.__getitem__(translation)
        except Exception:
            print("DIDNT FIND: " + translation)
            name = ""
        i18n.add_translation(translation, name, locale=language)
        return name
    return i18n.t(translation)
def example_i18n_translate0():
    i18n.add_translation('String in Language 1', 'String in Language 2')
    r = i18n.t('String in Language 1')  # String in Language 2
    print(r)
Exemple #4
0
# https://github.com/tuvistavie/python-i18n
# pip install python-i18n
import i18n
# python-i18n 은 파이썬에서 i18n 을 구현할 때 유용한 라이브러리이다.
# i18n 이란, internationalization 에서 첫 글자 i와 마지막 글자인 n을 그대로 쓰고 그 사이에 있는 18개 글자들은 숫자18로 줄인 말이다.
# internationalization(국제화) 는 이름 그대로, 다국어 시스템을 지원하여 각 나라 사람들이 자신들의 언어를 읽을 수 있게 하는 것이다.

# 다음은 가장 심플한 예제이다.
i18n.add_translation('사과', 'apple')
print(i18n.t('사과'))

# 다음처럼 placeholder 를 사용할 수도 있다.
i18n.add_translation('반가워', 'nice to meet you %{name} ~~')
print(i18n.t('반가워', name='Flouie'))

# python-i18n 은 YAML 과 JSON 파일 형식사용을 지원한다.
# 간단하게 하게 YAML 파일의 경로를 추가하고 번역할 수 있다.
# json 을 사용하고 싶으면 파일 포맷만 바꾸어 주면 된다
# i18n.set('file_format', 'json')
i18n.load_path.append('./')
print(i18n.t('foo.awesome python'))

# ROR 의 i18n 에 기반하여 Pluralization(다중화) 를 제공한다.
# 다중화는 사용할 때, 위의 예제와는 다르게 번역 값(t 함수에 키를 넣었을 때 반환되는 값) 을 딕셔너리로 하고, 딕셔너리 키가 한개 이상이어햐한다.
i18n.add_translation('awesome_python_issue', {
    'zero': 'There is no issue assigned to you.',
    'one': 'There is one issue assigned to you.',
    'few': 'There is %{count} issue assigned to you.',
    'many': 'There is %{count} issue assigned to you. hurry up!!'
})
print(i18n.t('awesome_python_issue', count=0))
Exemple #5
0
def run(args=sys.argv[1:]):
    """
        A convenient CLI to play with this bot
    """

    config = Config()

    parser = argparse.ArgumentParser(
        parents=[
            BotArgsHelper().parser(),
            jabber_arg_parser(),
            SignalArgsHelper().parser()
        ],
        description=
        "A bot that reacts to messages with given keywords by responding with a random translation"
    )
    # Core arguments for this bot
    parser.add_argument(
        "--keyword",
        "-k",
        dest="keywords",
        action="append",
        help=
        "A keyword a bot should react to, in any language (will write them & their translations into the file specified with --keywords-file)"
    )
    parser.add_argument("--keywords-file",
                        dest="keywords_files",
                        action="append",
                        help="File to load from and write keywords to")
    parser.add_argument('--locale',
                        '-l',
                        dest='locale',
                        default=config.locale,
                        help="Change default locale (e.g. 'fr_FR')")
    parser.add_argument("--languages-file",
                        dest="languages_file",
                        help="File to load from and write languages to")
    parser.add_argument(
        "--languages-likely",
        dest="languages_likely",
        default=config.languages_likely,
        help=
        "URI to Unicode's Likely Subtags (best language <-> country matches) in JSON format"
    )
    parser.add_argument("--shutdown",
                        dest="shutdown",
                        help="Shutdown keyword regular expression pattern")
    parser.add_argument(
        "--ibmcloud-url",
        dest="ibmcloud_url",
        help=
        "IBM Cloud API base URL (get it from your resource https://cloud.ibm.com/resources)"
    )
    parser.add_argument(
        "--ibmcloud-apikey",
        dest="ibmcloud_apikey",
        help=
        "IBM Cloud API key (get it from your resource : https://cloud.ibm.com/resources)"
    )

    #
    # Two-pass arguments parsing
    #
    config = parse_args_2pass(parser, args, config)
    #
    # From here the config object has default options from:
    #   1. hard-coded default values
    #   2. configuration file overrides
    #   3. command line overrides
    #
    # We can check the required options that could not be checked before
    # (because required arguments may have been set from the config file and not on the command line)
    #

    # i18n + l10n
    log.debug("Current locale : %s" % repr(locale.getlocale()))
    # e.g. if config.locale is 'en_US' we split it into : ['en', 'US'] ; dash separator is the RFC norm '-', but underscore '_' is used with Python
    lang = re.split(r'[_-]', config.locale)
    # See https://pypi.org/project/python-i18n/
    # FIXME Manually sets the locale : how come a Python library named 'i18n' doesn't take into account the Python locale by default ?
    i18n.set('locale', lang[0])
    log.debug("i18n locale : %s" % i18n.get('locale'))
    i18n.set('filename_format', 'i18n.{locale}.{format}'
             )  # Removing the namespace from keys is simpler for us
    i18n.set('error_on_missing_translation', True)
    for cd in config.config_dirs:
        i18n.load_path.append(cd)

    # These MUST be instanciated AFTER i18n has been configured !
    try:
        i18n.t('all_messages', message="")
    except:
        i18n.add_translation('all_messages', r'%{message}')
    if not config.shutdown:
        config.shutdown = i18n.t('Shutdown')

    if not config.ibmcloud_url:
        raise ValueError("Missing required parameter : --ibmcloud-url")
    if not config.ibmcloud_apikey:
        raise ValueError("Missing required parameter : --ibmcloud-apikey")

    # config.keywords is used if given
    # else, check for an existing keywords_file
    if not config.keywords:
        # keywords_files entries are tried either as a full path or as a filename relative to the config dirs
        # As a last resort, use all the 'keywords.json' found in the config directories
        keywords_paths_or_files = config.keywords_files
        if len(config.keywords_files) == 0:
            keywords_paths_or_files = ['keywords.json']
        # For each given keywords file given, check in all config dirs
        keywords_files_filtered = []
        for kf in keywords_paths_or_files:
            found = filter_files(
                [kf] + [os.path.join(dir, kf) for dir in config.config_dirs],
                should_exist=True,
                fallback_to=None)
            if found:
                keywords_files_filtered = keywords_files_filtered + found[0]
        config.keywords_files = keywords_files_filtered
        log.debug("Found the following keywords files : %s",
                  repr(config.keywords_files))
        # Convenience check to better warn the user and allow filenames relative to config dirs
        if len(config.keywords_files) == 0:
            # FIXME The bot should work without keywords or keywords_file (will be triggered only by other patterns)
            log.info(
                "Could not open any keywords file in %s. You can generate one with --keywords first or create the file indicated with --keywords-file"
                % repr(config.keywords_files))

    # Finds an existing languages_file
    # By default, uses 'languages.<lang>.json' or 'languages.json' in the config directory
    config.languages_file = filter_files([config.languages_file] + [
        os.path.join(dir, "languages.%s.json" % lang[0])
        for dir in config.config_dirs
    ] + [os.path.join(dir, 'languages.json') for dir in config.config_dirs],
                                         should_exist=True,
                                         fallback_to=1)[0]
    # Convenience check to better warn the user
    if not config.languages_file:
        raise ValueError(
            "Missing language file : please use only --languages-file to generate it automatically or --language for each target language"
        )

    # Finds a "likely language" file
    config.languages_likely = filter_files([config.languages_likely] + [
        os.path.join(dir, 'likelySubtags.json') for dir in config.config_dirs
    ],
                                           should_exist=True,
                                           fallback_to=1)[0]

    log.debug("Final configuration : %s", repr(obfuscate(vars(config))))

    # Creates the chat engine depending on the 'backend' parameter
    chatter = BotArgsHelper.chatter(config)

    #
    # Real start
    #

    bot = TransBot(keywords=config.keywords,
                   keywords_files=config.keywords_files,
                   languages_file=config.languages_file,
                   languages_likely=config.languages_likely,
                   locale=lang,
                   ibmcloud_url=config.ibmcloud_url,
                   ibmcloud_apikey=config.ibmcloud_apikey,
                   shutdown_pattern=config.shutdown,
                   chatter=chatter)
    status_result = bot.run()
    status = {'args': obfuscate(vars(config)), 'result': status_result}
    # Returns the full status to this module can be called CLI-style
    return status
import i18n

i18n.add_translation('money', {
    'zero': 'You do not have any money!',
    'one': 'You only have %{count} dollar...',
    'few': 'You just have %{count} dollars.',
    'many': 'God! You have %{count} dollars!!!'
})
print(i18n.t('money', count=0))
print(i18n.t('money', count=1))
print(i18n.t('money', count=5))
print(i18n.t('money', count=10000000))


#
# i18n.set("file_format", "json")
# i18n.load_path.append(".")
#
# i18n.set("locale", "fr")
# print(i18n.t("languages.inquiry"))
#
# i18n.set("locale", "en")
# print(i18n.t("languages.inquiry"))
#
# i18n.set("locale", "cn")
# print(i18n.t("languages.inquiry"))



import argparse
import sys
import os
import cairo
import locale
import i18n
import io

DOC_WIDTH = 1872  # 26 inches
DOC_HEIGHT = 2736  # 40 inches
DOC_NAME = "life_calendar.pdf"

i18n.set('locale', 'it_IT')

i18n.add_translation('First week of the new year',
                     'Inizio anno',
                     locale='it_IT')
i18n.add_translation('Week of your birthday', 'Compleanno', locale='it_IT')
i18n.add_translation('Weeks lived', 'Vissute', locale='it_IT')

XAXIS_DESC = "Settimane dell'anno"
YAXIS_DESC = "Anni di vita"

FONT = "Brocha"
BIGFONT_SIZE = 40
SMALLFONT_SIZE = 16
TINYFONT_SIZE = 14

MAX_TITLE_SIZE = 30
DEFAULT_TITLE = "CALENDARIO DELLA VITA"