Google Translate API is a powerful tool that can help you translate text from one language to another.

Using Python to call Google Translate API, you can easily integrate automatic translation capabilities in your application. Here are two ways on how to achieve this goal;

Method 1: Generate a translation request

This method performs a GET request on the Google Translate URL, obtains the webpage content, and then uses regular expressions to parse it to obtain the translation result;

This method requires the use of a VPN in mainland China;

import re
import html
from urllib import parse
import requests

GOOGLE_TRANSLATE_URL = 'http://translate.google.com/m?q=%s&tl=%s&sl=%s'

def translate(text, to_language="auto", text_language="auto"):

    text = parse.quote(text)
    url = GOOGLE_TRANSLATE_URL % (text,to_language,text_language)
    response = requests.get(url)
    data = response.text
    expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
    result = re.findall(expr, data)
    if (len(result) == 0):
        return ""

    return html.unescape(result[0])

print(translate("你吃饭了么?", "en","zh-CN")) #汉语转英语
print(translate("你吃饭了么?", "ja","zh-CN")) #汉语转日语
print(translate("about your situation", "zh-CN","en")) #英语转汉语

Program running results

Have you eaten?
食べましたか?
关于你的情况

Method 2: Use google-cloud-translate

google-cloud-translate is the official Python client library for the Google Cloud Translation API, providing an interface for interacting with the Google Translate API.

Below is a detailed guide on how to use google-cloud-translate, including installation, basic usage, and sample code.

1. Installation

Use pip to install google-cloud-translate;

pip install google-cloud-translate

2. Configure Google Cloud

Make sure you have set up a Google Cloud project and enabled the Translation API. You will also need a service account key file (JSON format) for authentication.

3. Sample code

from google.cloud import translate_v2 as translate
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('path/to/your/credentials.json')
client = translate.Client(credentials=credentials)

def translate_text(text, target_language='en'):
    result = client.translate(text, target_language=target_language)
    return result['translatedText']

text_to_translate = "你好,世界"
translated_text = translate_text(text_to_translate, 'en')
print("Translated Text:", translated_text)