Using translate in python

Using the Translator¶

Imagine you want to translate the string “Symfony” into French:

from python_translate.translations import Translator from python_translate.loader import DictLoader translator = new Translator('fr_FR') translator.add_loader('dict', DictLoader()) translator.add_resource('dict',  'Symfony!': "J'aime python_translate!", >, 'fr_FR') print translator->trans('Symfony!') 

In this example, the message “Symfony!” will be translated into the locale set in the constructor ( fr_FR ) if the message exists in one of the message catalogs.

Message Placeholders¶

Sometimes, a message containing a variable needs to be translated:

// . translated = translator.trans('Hello ' + name) print translated 

However, creating a translation for this string is impossible since the translator will try to look up the exact message, including the variable portions (e.g. “Hello Ryan” or “Hello Fabien”). Instead of writing a translation for every possible iteration of the name variable, you can replace the variable with a “placeholder”:

translated = translator.trans( 'Hello ', 'name': name> ) print translated 

python_translate will now look for a translation of the raw message ( Hello ) and then replace the placeholders with their values. Creating a translation is done just as before:

The placeholders are simply python formating placeholders.

As you’ve seen, creating a translation is a two-step process:

  1. Abstract the message that needs to be translated by processing it through the Translator .
  2. Create a translation for the message in each locale that you choose to support.

The second step is done by creating message catalogs that define the translations for any number of different locales.

Creating Translations¶

Translation files consist of a series of id-translation pairs for the given domain and locale. The source is the identifier for the individual translation, and can be the message in the main locale (e.g. “Symfony is great”) of your application or a unique identifier (e.g. symfony.great — see the sidebar below).

Translation files can be created in several different formats, Yaml being the recommended format. These files are parsed by one of the loader classes.

Using Real or Keyword Messages

This example illustrates the two different philosophies when creating messages to be translated:

translator.trans('Symfony') translator.trans('symfony.great') 

In the first method, messages are written in the language of the default locale (English in this case). That message is then used as the “id” when creating translations.

In the second method, messages are actually “keywords” that convey the idea of the message. The keyword message is then used as the “id” for any translations. In this case, translations must be made for the default locale (i.e. to translate symfony.great to Symfony is great ).

The second method is handy because the message key won’t need to be changed in every translation file if you decide that the message should actually read “Symfony is really great” in the default locale.

The choice of which method to use is entirely up to you, but the “keyword” format is often recommended.

Additionally, the yaml file format supports nested ids to avoid repeating yourself if you use keywords instead of real text for your ids:

The multiple levels are flattened into single id/translation pairs by adding a dot ( . ) between every level, therefore the above examples are equivalent to the following:

Pluralization¶

Message pluralization is a tough topic as the rules can be quite complex. For instance, here is the mathematical representation of the Russian pluralization rules:

((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && (number % 10 = 20))) ? 1 : 2 )

As you can see, in Russian, you can have three different plural forms, each given an index of 0, 1 or 2. For each form, the plural is different, and so the translation is also different.

When a translation has different forms due to pluralization, you can provide all the forms as a string separated by a pipe ( | ):

'There is one apple|There are  apples' 

To translate pluralized messages, use the python_translate.translations.Translator.transchoice method

translator.transchoice( ‘There is one apple|There are apples’, 10,

)

The second argument ( 10 in this example) is the number of objects being described and is used to determine which translation to use and also to populate the placeholder.

Based on the given number, the translator chooses the right plural form. In English, most words have a singular form when there is exactly one object and a plural form for all other numbers (0, 2, 3…). So, if count is 1 , the translator will use the first string ( There is one apple ) as the translation. Otherwise it will use There are apples .

Here is the French translation:

'Il y a pomme|Il y a pommes'

Even if the string looks similar (it is made of two sub-strings separated by a pipe), the French rules are different: the first form (no plural) is used when count is 0 or 1 . So, the translator will automatically use the first string ( Il y a pomme ) when count is 0 or 1 .

Each locale has its own set of rules, with some having as many as six different plural forms with complex rules behind which numbers map to which plural form. The rules are quite simple for English and French, but for Russian, you’d may want a hint to know which rule matches which string. To help translators, you can optionally “tag” each string:

'one: There is one apple|some: There are apples' 'none_or_one: Il y a pomme|some: Il y a pommes'

The tags are really only hints for translators and don’t affect the logic used to determine which plural form to use. The tags can be any descriptive string that ends with a colon ( : ). The tags also do not need to be the same in the original message as in the translated one.

As tags are optional, the translator doesn’t use them (the translator will only get a string based on its position in the string).

Explicit Interval Pluralization¶

The easiest way to pluralize a message is to let the Translator use internal logic to choose which string to use based on a given number. Sometimes, you’ll need more control or want a different translation for specific cases (for 0 , or when the count is negative, for example). For such cases, you can use explicit math intervals:

' There are no apples| There is one apple|]1,19] There are apples|[20,Inf] There are many apples'

The intervals follow the ISO 31-11 notation. The above string specifies four different intervals: exactly 0 , exactly 1 , 2-19 , and 20 and higher.

Note that interval definitions will not be present in a translated message, and they have nothing to do with placeholders such as . They will not be formatted, just removed before you get to see them.

You can also mix explicit math rules and standard rules. In this case, if the count is not matched by a specific interval, the standard rules take effect after removing the explicit rules:

' There are no apples|[20,Inf] There are many apples|There is one apple|a_few: There are apples'

For example, for 1 apple, the standard rule There is one apple will be used. For 2-19 apples, the second standard rule There are apples will be selected.

You may even represent a finite set of numbers:

Or numbers between two other numbers:

The left delimiter can be [ (inclusive) or ] (exclusive). The right delimiter can be [ (exclusive) or ] (inclusive). Beside numbers, you can use -Inf and +Inf for the infinite.

Forcing the Translator Locale¶

When translating a message, the Translator uses the specified locale or the fallback locale if necessary. You can also manually specify the locale to use for translation:

translator.trans( 'Symfony', <>, 'messages', 'fr_FR' ) translator.transchoice( '  There are no apples|  There is one apple|]1,Inf[ There are  apples', 10, 'count': 10>, 'messages', 'fr_FR' ) 

Retrieving the Message Catalogue¶

In case you want to use the same translation catalogue outside your application (e.g. use translation on the client side), it’s possible to fetch raw translation messages. Just specify the required locale:

messages = translator.get_messages('fr_FR') 

The messages variable will have the following structure:

 'messages':  'Hello world': 'Bonjour tout le monde', >, 'validators':  'Value should not be empty': 'Valeur ne doit pas être vide', 'Value is too long': 'Valeur est trop long', > > 

© Copyright 2015, Adam Zieliński. Revision 0aee83f4 .

Versions latest Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

translate 3.6.1

This is a simple, yet powerful command line translator with google translate behind it. You can also use it as a Python module in your code.

Ссылки проекта

Статистика

Метаданные

Лицензия: MIT License (MIT)

Метки translate, translation, command, line

Сопровождающие

Классификаторы

Описание проекта

Translate is a simple but powerful translation tool written in python with with support for multiple translation providers. By now we offer integration with Microsoft Translation API, Translated MyMemory API, LibreTranslate, and DeepL’s free and pro APIs

Why Should I Use This?

The biggest reason to use translate is to make translations in a simple way without the need of bigger effort and can be used as a translation tool like command line

Installation

Or, you can download the source and

Prefix ‘sudo’ if you encounter a problem.

Features

  • Translate your output in real time
  • Do translation in your terminal using the command line

Usage

$ translate-cli -t zh  这是一支笔 by: MyMemory

Options

$ translate-cli --help __main__.py  TEXT.  Python  line tool to make online translations Example: $ translate-cli -t zh the book is on the table 碗是在桌子上。 Available languages: https://en.wikipedia.org/wiki/ISO_639-1 Examples:  en, ja, ko, pt, zh, zh-TW, .  --version Show the version and exit. --generate-config-file Generate the config file using a Wizard and exit. -f, --from TEXT Sets the language of the text being translated. The default value is  -t, --to TEXT Set the language you want to translate. -p, --provider TEXT Set the provider you want to use. The default value is  --secret_access_key TEXT Set the secret access key used to get provider oAuth token. -o, --output_only Set to display the translation only. --help Show this message and exit.

Change Default Languages

  autodetect  de  mymemory The cfg is not for use as a Python module.

or run the command line and follow the steps:

$ translate-cli —generate-config-file from to: Access Key

Use As A Python Module

The result is usually a unicode string.

Use a different translation provider

The DeepL Provider

To use DeepL’s pro API, pass an additional parameter called pro to the Translator object and set it to True and use your pro authentication key as the secret_access_key

Documentation

Check out the latest translate documentation at Read the Docs

Contributing

Please send pull requests, very much appreciated.

  1. Fork the repository on GitHub.
  2. Make a branch off of master and commit your changes to it.
  3. Install requirements. pip install -r requirements-dev.txt
  4. Install pre-commit. pre-commit install
  5. Run the tests with py.test -vv -s
  6. Create a Pull Request with your contribution

Changelog

3.6.1

3.5.0

3.4.1

3.4.0

  • Refactor: Create a folder to add all providers instead to let in a single file
  • Add Microsoft provider
  • Add more documentation to all providers (Translated-MyMemory and Microsoft Translator)
  • Add arguments to change the default provider using translate-cli

3.3.0

  • Refactor translate-cli (command line interface) Using Click library instead of ArgParser
  • Unify translate-cli and main to avoid duplicate code
  • Add documentation to be used on helper commands on translate-cli
  • Remove unnecessary code
  • Refactor setup to complete information in the PKG-INFO used by PyPI

3.2.1

3.2.0

3.1.0

  • Apply Solid Principles
  • Organize Project
  • Add pre-commit, pytest
  • Add new Make file
  • Add new test cases

3.0.0

  • General Refactor
  • Remove urllib to use requests
  • Refactor methods names removing google from then
  • Apply PEP8
  • Change contructor to keep it the code simple

2.0.0 (2017-11-08)

Источник

Читайте также:  Python if multiple conditions and or
Оцените статью