📜  西班牙语到英语 - Python (1)

📅  最后修改于: 2023-12-03 14:57:21.019000             🧑  作者: Mango

Spanish to English - Python

Introduction

This is a program that translates Spanish text into English using Python. With the help of the googletrans Python library, we can easily convert Spanish language into English with just a few lines of code.

Prerequisites

Before running this program, make sure you have the following installed:

  • Python 3 (https://www.python.org/downloads/)
  • googletrans library (pip install googletrans)
Code
from googletrans import Translator

def translate_spanish_to_english(text):
    translator = Translator()
    translation = translator.translate(text, src='es', dest='en')
    return translation.text

spanish_text = "¡Hola, cómo estás?"
english_text = translate_spanish_to_english(spanish_text)
print(english_text)
Code Explanation
  1. We import the Translator class from the googletrans library.
  2. translate_spanish_to_english function is defined, which takes a Spanish text as input.
  3. An instance of Translator class is created.
  4. The translate method is called on the translator object, which takes the text to be translated and the source (Spanish) and destination (English) languages as parameters. The translated text is stored in the translation object.
  5. The translated text is returned from the function.
  6. We define a Spanish text and call the translate_spanish_to_english function with that text.
  7. The translated English text is printed.
Conclusion

This program provides a simple way to translate Spanish text to English using Python. By using the googletrans library, we can effortlessly perform language translation tasks.