translate_sentence
translate_sentence
Module that fetches a sentence’s translation and metadata through Google Translate.
Functions
| Name | Description |
|---|---|
| translate_sentence | Translate an input sentence into a target language using Google Translate. |
translate_sentence
translate_sentence.translate_sentence(
sentence,
target_language,
source_language=None,
)Translate an input sentence into a target language using Google Translate.
This function sends the input sentence to Google Translate and returns the translated text along with additional metadata. By default, the source language is automatically detected by the translation service. If an error occurs during translation, the original sentence is returned and error information is included in the output.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| sentence | string | The input sentence to be translated. | required |
| target_language | string | The target language code (e.g., ‘es’ for Spanish, ‘fr’ for French). | required |
| source_language | string | The source language code of the input sentence. If None, the source language is automatically detected. Default is None. | None |
Returns
| Name | Type | Description |
|---|---|---|
| dict | A dictionary containing the translation result and metadata with the following keys: - ‘translated_text’ : string The translated sentence. - ‘source_language’ : string The detected or specified source language code. - ‘target_language’ : string The target language code used for translation. - ‘error’ : string or None An error message if the translation failed; otherwise None. |
Raises
| Name | Type | Description |
|---|---|---|
| TypeError | If sentence is not a string, target_language is not a string, or source_language is not a string or None. |
Examples
>>> translate_sentence("Hello world", "es")
>>> translate_sentence("Bonjour tout le monde", "en")
>>> translate_sentence("Hello world", "fr", source_language="en")