精通 Google Cloud Translation API 与 Python:开发者指南

发布: (2026年1月20日 GMT+8 13:07)
6 min read
原文: Dev.to

Source: Dev.to

📋 前置条件

  • Google 账户。
  • 信用卡(即使在免费额度内,也需要用于 Google Cloud 计费账户的设置)。
  • 在机器上已安装 Python 3.7+。
  • 用于安装软件包的 pip

1️⃣ 创建 Google Cloud 项目

  1. 打开 Cloud Console

    • 在浏览器中访问 。
  2. 创建新项目

    • 点击左上角的项目下拉菜单(通常显示 “My First Project” 或您当前的项目名称)。
    • 在弹出窗口中,点击 “New Project”
    • 项目名称: Python-Translation-Project(或您喜欢的任何明确名称)。
    • 位置: 可选 – 如果有组织/文件夹,请选择,否则保持 “No organization”。
    • 点击 “Create” 并等待片刻完成资源配置。
  3. 选择您的新项目

    • 完成后,从下拉菜单中选择该项目。

2️⃣ 启用 Cloud Translation API

  1. 打开 API 库

    • 点击左上角的导航菜单 (☰)。
    • 前往 APIs & Services → Library
  2. 搜索并启用

    • 在搜索栏中输入 “Cloud Translation API”
    • 点击 “Cloud Translation API” 结果。
    • 按下大的蓝色 “ENABLE” 按钮。

故障排除: 如果稍后看到 403 Forbidden 错误,请返回此步骤。启用可能需要几分钟才能传播,或者该 API 可能未在您的代码使用的项目中启用。

3️⃣ 创建服务账号(用于身份验证)

  1. 打开凭据

    • 点击导航菜单 (☰)。
    • 前往 APIs & Services → Credentials
  2. 创建服务账号

    • 点击 + CREATE CREDENTIALSService account
    • 服务账号名称: translation-service-account(或类似)。
    • 描述(可选): “Service account for Python Translation API”。
    • 点击 “CREATE AND CONTINUE”
  3. 授予权限

    • “Grant this service account access to project” 下,点击 Select a role
    • 搜索并选择 “Cloud Translation API User”
    • 点击 “CONTINUE”
  4. 完成

    • (可选)跳过 “Grant users access to this service account”。
    • 点击 “DONE”
  5. 下载 JSON 密钥

    • 返回 Credentials 页面,在 Service Accounts 下找到新建的服务账号。
    • 点击其电子邮件地址 → Keys 选项卡 → ADD KEY → Create new key
    • 选择 JSON(默认且推荐)并点击 CREATE
    • .json 文件会自动下载。请妥善保管此文件——它是服务账号的“密码”。

Source:

4️⃣ 项目设置与安装(本地机器)

4.1 创建项目目录

mkdir my-translation-app
cd my-translation-app

4.2 移动你的凭证

mkdir credentials
mv /path/to/your/downloaded-key.json credentials/google_key.json

(为简化起见,将文件重命名为 google_key.json。)

4.3 设置虚拟环境

python3 -m venv venv
# 在 macOS/Linux 上
source venv/bin/activate
# 在 Windows 上
venv\Scripts\activate

4.4 安装客户端库

pip install google-cloud-translate

5️⃣ 编写翻译脚本

在项目根目录创建一个名为 translate_text.py 的文件,并粘贴以下代码:

import os
from google.cloud import translate_v2 as translate

# 👉 IMPORTANT: Point to your service‑account key file.
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "credentials/google_key.json"

def translate_single_text(text: str, target_language_code: str) -> None:
    """
    Translates a single piece of text to the target language.
    """
    # Initialise the client
    client = translate.Client()

    # Perform translation
    result = client.translate(text, target_language=target_language_code)

    print(f"Original Text: {text}")
    print(f"Target Language: {target_language_code}")
    print(f"Translated Text: {result['translatedText']}")
    print(f"Detected Source Language: {result['detectedSourceLanguage']}")

if __name__ == "__main__":
    my_text = "Hello world, this is a test of the Google Cloud Translation API."

    # Example translations
    translate_single_text(my_text, "es")   # Spanish
    print("-" * 30)
    translate_single_text(my_text, "fr")   # French
    print("-" * 30)
    translate_single_text("Wie geht es dir?", "en")  # German → English

5.1 运行脚本

python translate_text.py

您应该会看到类似以下的输出:

Original Text: Hello world, this is a test of the Google Cloud Translation API.
Target Language: es
Translated Text: Hola mundo, esto es una prueba de la API de traducción de Google Cloud.
Detected Source Language: en
------------------------------
Original Text: Hello world, this is a test of the Google Cloud Translation API.
Target Language: fr
Translated Text: Bonjour le monde, ceci est un test de l'API de traduction Google Cloud.
Detected Source Language: en
------------------------------
Original Text: Wie geht es dir?
Target Language: en
Translated Text: How are you?
Detected Source Language: de

🎉 接下来是什么?

  • 探索更多语言 – 使用任何 ISO‑639‑1 代码(例如 ja 表示日语)。
  • 批量翻译 – 在一次请求中翻译多个字符串。
  • 高级功能 – 术语表支持、模型选择等。

祝编码愉快! 🚀

翻译 API 结果

目标语言: es
检测到的源语言: en

原文

你好,世界,这是对 Google Cloud 翻译 API 的测试。

译文

你好,世界,这是对 Google Cloud 翻译 API 的测试。


目标语言: fr
检测到的源语言: en

原文

你好,世界,这是对 Google Cloud 翻译 API 的测试。

译文

你好,世界,这是对 Google Cloud 翻译 API 的测试。


原文

Wie geht es dir?

目标语言: en
检测到的源语言: de

译文

你好吗?

.gitignore

在将任何代码推送到 GitHub 之前,请在 my-translation-app 目录的根目录下创建一个 .gitignore 文件。

# Credentials and Secrets
credentials/
.env

# Python Environment
venv/
__pycache__/
*.py[cod]

这可以防止诸如 google_key.json 之类的敏感文件以及你的虚拟环境意外地被提交到版本控制中。

下一步

您已经完成了:

  1. 已设置 Google Cloud 项目。
  2. 已启用翻译 API。
  3. 已配置安全的服务账户。
  4. 已编写用于翻译文本的 Python 脚本。

此基础设置对于更高级的翻译任务至关重要,例如将该服务集成到更大的数据管道或 Web 应用程序中。

翻译愉快!

Back to Blog

相关文章

阅读更多 »