📜  谷歌将英语翻译成中文 (1)

📅  最后修改于: 2023-12-03 15:12:12.689000             🧑  作者: Mango

谷歌翻译API介绍

谷歌翻译API是一种文本翻译服务,可以将一种语言翻译成另一种语言。您可以使用该API将英语翻译成中文或其他100多种语言。

API使用步骤
步骤1:获取API密钥

要使用谷歌翻译API,您需要在Google Cloud Console上创建一个项目并启用API。

  1. 登录Google Cloud Console
  2. 创建一个新项目或选择一个现有项目
  3. 在左侧导航栏中选择“API和服务”>“Library”>“Google Cloud Translation API”,然后单击“启用”。

要使用API,您需要获取API密钥。在Cloud Console中,导航到API Credentials页面,然后单击“Create credentials”>“API密钥”。

步骤2:安装Google Cloud SDK

Google Cloud SDK是一个命令行工具,您需要在本地安装此工具以使用Google Cloud Console。

  1. 访问Google Cloud SDK官网https://cloud.google.com/sdk/docs/install
  2. 根据您的操作系统下载和安装Google Cloud SDK
步骤3:进行API请求

使用Google Cloud SDK,在命令行中运行以下命令将英语文本翻译成中文:

$ gcloud auth application-default login
$ curl -s -X POST -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer "$(gcloud auth application-default print-access-token)"' \
    --data "{
  'q': 'Hello world',
  'source': 'en',
  'target': 'zh-CN',
  'format': 'text'
}" "https://translation.googleapis.com/language/translate/v2"

上述命令将英语文本“Hello world”翻译成中文。

步骤4:解析API响应

API响应是一段JSON格式的文本,您需要解析响应以获取翻译文本。以下是一个解析JSON的Python示例:

import json
import urllib.request

query = "Hello world"
source = "en"
target = "zh-CN"
url = f"https://translation.googleapis.com/language/translate/v2?q={query}&source={source}&target={target}&format=text"

with urllib.request.urlopen(url) as response:
    data = json.loads(response.read().decode())

print(data['data']['translations'][0]['translatedText'])

上述代码将英文文本“Hello world”翻译成中文,打印出翻译的结果。

API限制和定价

谷歌翻译API有一些限制:

  • 每个月免费翻译500,000个字符,超出部分需要付费
  • 最大文本长度是32,768个字符
  • API每秒最多只能进行100个翻译请求

有关在Google Cloud Console中使用API的完整信息,请访问Google翻译API官方文档

参考资料