To work with the Google Translate API using Python, you can use the googletrans
library, which is a wrapper around the Google Translate API. Below is a simple script demonstrating how to use this library to translate text.
First, you need to install the library:
pip install googletrans==4.0.0-rc1
Here’s a basic example script to translate text using the googletrans
library:
from googletrans import Translator
def translate_text(text, src_lang='auto', dest_lang='en'):
translator = Translator()
try:
translated = translator.translate(text, src=src_lang, dest=dest_lang)
return translated.text
except Exception as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
# Example usage
original_text = "Hola, ¿cómo estás?"
src_language = 'es' # Spanish
dest_language = 'en' # English
translated_text = translate_text(original_text, src_language, dest_language)
if translated_text:
print(f"Original text: {original_text}")
print(f"Translated text: {translated_text}")
This script performs the following steps:
- Imports the
Translator
class from thegoogletrans
library. - Defines a function
translate_text
that takes the text to be translated, the source language, and the target language as arguments. - Uses the
Translator
object to perform the translation and handles any exceptions that might occur. - In the
if __name__ == "__main__":
block, demonstrates how to use thetranslate_text
function with an example.
You can modify the src_language
and dest_language
variables to translate between different languages. The src_lang
parameter can be set to 'auto'
to automatically detect the source language.
Feel free to expand on this script or integrate it into a larger application as needed.
Comments (0)
There are no comments here yet, you can be the first!