杰瑞科技汇

Python googletrans怎么用?翻译效果如何?

Of course! The googletrans library is a popular and easy-to-use Python package for translating text using the Google Translate service. It's a great tool for quick translations and personal projects.

Python googletrans怎么用?翻译效果如何?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from installation to advanced usage.


Installation

First, you need to install the library. The most common and recommended version is googletrans==4.0.0-rc1. It's important to specify the version because newer, unofficial versions have caused issues in the past.

Open your terminal or command prompt and run:

pip install googletrans==4.0.0-rc1

Basic Usage

The core of the library is the Translator class. You create an instance of it and then use its methods to translate text.

Python googletrans怎么用?翻译效果如何?-图2
(图片来源网络,侵删)

A Simple Translation

The most common method is translate(). You can specify the source language (src) and the destination language (dest). If you don't specify the source language, Google Translate will try to detect it automatically.

from googletrans import Translator
# Create a Translator object
translator = Translator()
# --- Example 1: Auto-detect source language ---
text_to_translate = "Hello, how are you?"
result = translator.translate(text_to_translate, dest='es')
print(f"Original text: {text_to_translate}")
print(f"Translated text: {result.text}")
print(f"Source language detected: {result.src}")
print("-" * 20)
# --- Example 2: Specify source and destination languages ---
text_to_translate = "Je suis étudiant."
result = translator.translate(text_to_translate, src='fr', dest='en')
print(f"Original text: {text_to_translate}")
print(f"Translated text: {result.text}")
print(f"Source language: {result.src}")
print(f"Destination language: {result.dest}")

Output:

Original text: Hello, how are you?
Translated text: Hola, ¿cómo estás?
Source language detected: en
--------------------
Original text: Je suis étudiant.
Translated text: I am a student.
Source language: fr
Destination language: en

Understanding the Translation Result Object

When you call translator.translate(), it returns a Translated object. This object contains several useful attributes:

  • result.text: The translated string. This is what you'll use most often.
  • result.src: The language code of the source text (e.g., 'en', 'fr', 'es').
  • result.dest: The language code of the destination language (e.g., 'en', 'fr', 'es').
  • result.origin: The original text that was passed to the translator.
  • result.extra_data: A dictionary containing extra information, like possible alternative translations.
  • result.pronunciation: The pronunciation of the translated text (if available).
from googletrans import Translator
translator = Translator()
text = "Good morning"
result = translator.translate(text, dest='ja')
print(f"Original: {result.origin}")
print(f"Translated: {result.text}")
print(f"Pronunciation: {result.pronunciation}")
print(f"Source Language: {result.src} -> Destination Language: {result.dest}")

Output:

Python googletrans怎么用?翻译效果如何?-图3
(图片来源网络,侵删)
Original: Good morning
Translated: おはようございます
Pronunciation: ohayō gozaimasu
Source Language: en -> Destination Language: ja

Advanced Features

A. Translating a List of Sentences

You can efficiently translate a list of texts by passing the list directly to the translate() method.

from googletrans import Translator
translator = Translator()
sentences = [
    "Hello world",
    "How are you?",
    "This is a test."
]
# Translate all sentences to French
results = translator.translate(sentences, dest='fr')
for result in results:
    print(f"{result.origin} -> {result.text}")

Output:

Hello world -> Bonjour le monde
How are you? -> Comment allez-vous ?
This is a test. -> Ceci est un test.

B. Detecting Language

If you just want to know what language a piece of text is in, use the detect() method.

from googletrans import Translator
translator = Translator()
text1 = "This is an English sentence."
text2 = "Ceci est une phrase en français."
print(f"'{text1}' is detected as: {translator.detect(text1).lang}")
print(f"'{text2}' is detected as: {translator.detect(text2).lang}")

Output:

'This is an English sentence.' is detected as: en
'Ceci est une phrase en français.' is detected as: fr

The detect() method also returns a full object with more details like confidence.

detection = translator.detect(text1)
print(f"\nFull detection object for '{text1}':")
print(f"  Language: {detection.lang}")
print(f"  Confidence: {detection.confidence}")

Output:

Full detection object for 'This is an English sentence.':
  Language: en
  Confidence: 0.9999923706054688

Language Codes

You can use either full language names (like 'english') or two-letter ISO 639-1 codes (like 'en'). Using codes is more common and robust.

Language Code
English en
Spanish es
French fr
German de
Chinese (Simplified) zh-cn or zh
Chinese (Traditional) zh-tw
Japanese ja
Korean ko
Russian ru
Arabic ar
Auto-detect auto

Important Caveats and Troubleshooting

A. Rate Limiting and Errors

The googletrans library is an unofficial wrapper. It sends requests to the public Google Translate website. This means:

  • You can get blocked. If you make too many requests in a short period, Google might temporarily block your IP address.
  • It can break. If Google changes its website's backend code, the library might stop working without any prior notice.

Best Practice: For any serious application, it's better to use a more reliable and robust service like the official Google Cloud Translation API (which is paid) or other dedicated translation APIs.

B. Common Errors

  • AttributeError: 'NoneType' object has no attribute 'text' This usually means the translation failed. The most common reason is that Google has blocked your request due to rate limiting. Try waiting a few minutes or reducing the number of requests.

  • JSONDecodeError This error also often points to a change in Google's backend or a temporary block.

C. Alternatives to googletrans

If googletrans stops working, here are some good alternatives:

  1. deep-translator: A more modern and actively maintained library that supports multiple translation services (Google, Libre, Yandex, etc.).

    pip install deep-translator
    from deep_translator import GoogleTranslator
    text = "Hello, world!"
    translated = GoogleTranslator(source='auto', target='de').translate(text)
    print(translated) # Guten Tag, Welt!
  2. google-cloud-translate: The official, powerful, and robust library for Google's paid Cloud Translation API. This is the best choice for production applications.


Summary

Task Code Snippet
Install pip install googletrans==4.0.0-rc1
Basic Translate translator = Translator()
result = translator.translate("Hello", dest='fr')
print(result.text)
Translate List results = translator.translate(["hi", "bye"], dest='es')
Detect Language detection = translator.detect("Bonjour")
print(detection.lang)
Get Pronunciation result = translator.translate("Hello", dest='ja')
print(result.pronunciation)

For most quick scripts and personal projects, googletrans is a fantastic and easy-to-use tool. Just be mindful of its limitations and have a backup plan for more critical applications.

分享:
扫描分享到社交APP
上一篇
下一篇