Skip to content

Latest commit

 

History

History
123 lines (96 loc) · 3.62 KB

File metadata and controls

123 lines (96 loc) · 3.62 KB

Using the API

With Google Translate, you can dynamically translate text between thousands of language pairs. The Google Translate API lets websites and programs integrate with Google Translate programmatically. Google Translate API is available as a paid service. See the Pricing and FAQ pages for details.

Authentication / Configuration

Methods

To create a client:

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key')

By default, the client targets English when doing detections and translations, but a non-default value can be used as well:

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key', target_language='es')

The Google Translate API has three supported methods, and they map to three methods on a client: :meth:`~google.cloud.translate.client.Client.get_languages`, :meth:`~google.cloud.translate.client.Client.detect_language` and :meth:`~google.cloud.translate.client.Client.translate`.

To get a list of languages supported by Google Translate

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key')
>>> client.get_languages()
[
    {
        'language': 'af',
        'name': 'Afrikaans',
    },
     ...
]

To detect the language that some given text is written in:

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key')
>>> client.detect_language(['Me llamo', 'I am'])
[
    {
        'confidence': 0.25830904,
        'input': 'Me llamo',
        'language': 'es',
    }, {
        'confidence': 0.17112699,
        'input': 'I am',
        'language': 'en',
    },
]

The confidence value is an optional floating point value between 0 and 1. The closer this value is to 1, the higher the confidence level for the language detection. This member is not always available.

To translate text:

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key')
>>> client.translate('koszula')
{
    'translatedText': 'shirt',
    'detectedSourceLanguage': 'pl',
    'input': 'koszula',
}

or to use a non-default target language:

>>> from google.cloud import translate
>>> client = translate.Client('my-api-key')
>>> client.translate(['Me llamo Jeff', 'My name is Jeff'],
...                  target_language='de')
[
    {
        'translatedText': 'Mein Name ist Jeff',
        'detectedSourceLanguage': 'es',
        'input': 'Me llamo Jeff',
    }, {
        'translatedText': 'Mein Name ist Jeff',
        'detectedSourceLanguage': 'en',
        'input': 'My name is Jeff',
    },
]