快速入门:通过 Python 使用双语字典查找字词Quickstart: Look up words with bilingual dictionary using Python

本快速入门介绍如何使用 Python 和文本翻译 REST API 查找指定文本的备用翻译和用法示例。In this quickstart, you'll learn how to find alternate translations and usage examples for a specified text using Python and the Translator Text REST API.

此快速入门需要包含文本翻译资源的 Azure 认知服务帐户This quickstart requires an Azure Cognitive Services account with a Translator Text resource. 如果没有帐户,可以使用试用帐户获取订阅密钥。If you don't have an account, you can use the trial to get a subscription key.


如果你想一次看到所有代码,这个示例的源代码可以在 GitHub 上找到。If you'd like to see all the code at once, the source code for this sample is available on GitHub.


本快速入门需要:This quickstart requires:

  • Python 2.7.x 或 3.xPython 2.7.x or 3.x
  • 适用于文本翻译的 Azure 订阅密钥An Azure subscription key for Translator Text

创建一个项目并导入必需的模块Create a project and import required modules

使用喜欢的 IDE 或编辑器创建一个新 Python 项目,或在桌面上创建新的文件夹。Create a new Python project using your favorite IDE or editor, or create a new folder on your desktop. 将此代码片段复制到项目/文件夹的 dictionary-lookup.py 文件中。Copy this code snippet into your project/folder into a file named dictionary-lookup.py.

# -*- coding: utf-8 -*-
import os
import requests
import uuid
import json


如果尚未使用这些模块,则需在运行程序之前安装它们。If you haven't used these modules you'll need to install them before running your program. 若要安装这些包,请运行 pip install requests uuidTo install these packages, run: pip install requests uuid.

第一个注释告知 Python 解释器使用 UTF-8 编码。The first comment tells your Python interpreter to use UTF-8 encoding. 然后导入必需的模块,以便从环境变量读取订阅密钥、构造 HTTP 请求、创建唯一标识符,以及处理文本翻译 API 返回的 JSON 响应。Then required modules are imported to read your subscription key from an environment variable, construct the http request, create a unique identifier, and handle the JSON response returned by the Translator Text API.

设置订阅密钥、基 URL 和路径Set the subscription key, base url, and path

此示例将尝试从环境变量 TRANSLATOR_TEXT_KEY 读取文本翻译订阅密钥。This sample will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. 如果不熟悉环境变量,则可将 subscriptionKey 设置为字符串并注释掉条件语句。If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

将以下代码复制到项目中:Copy this code into your project:

# Checks to see if the Translator Text subscription key is available
# as an environment variable. If you are setting your subscription key as a
# string, then comment these lines out.
if 'TRANSLATOR_TEXT_KEY' in os.environ:
    subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
    print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
# If you want to set your subscription key as a string, uncomment the line
# below and add your subscription key. Then, be sure to delete your "os" import.
# subscriptionKey = 'put_your_key_here'
region = 'put_your_region_here'

文本翻译全局终结点设置为 base_urlThe Translator Text global endpoint is set as the base_url. path 设置 dictionary/lookup 路由并确定我们需使用 API 的版本 3。path sets the dictionary/lookup route and identifies that we want to hit version 3 of the API.

params 用于设置源和输出语言。The params are used to set the source and output languages. 在此示例中,我们将使用英语和西班牙语:enesIn this sample we're using English and Spanish: en and es.


有关终结点、路由和请求参数的详细信息,请参阅文本翻译 API 3.0:字典查找For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Dictionary Lookup.

base_url = 'https://api.translator.azure.cn'
path = '/dictionary/lookup?api-version=3.0'
params = '&from=en&to=es'
constructed_url = base_url + path + params

添加标头Add headers

若要对请求进行身份验证,最容易的方法是将订阅密钥作为 Ocp-Apim-Subscription-Key 标头传入,这是我们在此示例中使用的方法。The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. 替代方法是交换订阅密钥来获取访问令牌,将访问令牌作为 Authorization 标头传入,以便对请求进行验证。As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request. 有关详细信息,请参阅身份验证For more information, see Authentication.

将以下代码片段复制到项目中。Copy this code snippet into your project:

headers = {
    'Ocp-Apim-Subscription-Key': subscriptionKey,
    'Ocp-Apim-Subscription-Region': region,
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())

如果使用的是认知服务多服务订阅,则还必须在请求参数中包括 Ocp-Apim-Subscription-RegionIf you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. 详细了解如何使用多服务订阅进行身份验证Learn more about authenticating with the multi-service subscription.

创建查找备用翻译的请求Create a request to find alternate translations

定义要查找其翻译的字符串:Define the string (or strings) that you want to find translations for:

# You can pass more than one object in body.
body = [{
    'text': 'Elephants'

接下来,请使用 requests 模块创建一个 POST 请求。Next, we'll create a POST request using the requests module. 它使用三个参数:串联的 URL、请求标头和请求正文:It takes three arguments: the concatenated URL, the request headers, and the request body:

request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()

最后一步是输出结果。The last step is to print the results. 以下代码片段通过将密钥排序、设置缩进以及声明项和密钥分隔符来美化结果。This code snippet prettifies the results by sorting the keys, setting indentation, and declaring item and key separators.

print(json.dumps(response, sort_keys=True, indent=4,
                 ensure_ascii=False, separators=(',', ': ')))

将其放在一起Put it all together

就是这样,你已构建了一个简单的程序。该程序可以调用文本翻译 API 并返回 JSON 响应。That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. 现在,可以运行该程序了:Now it's time to run your program:

python alt-translations.py

如果希望将你的代码与我们的进行比较,请查看 GitHub 上提供的完整示例。If you'd like to compare your code against ours, the complete sample is available on GitHub.

示例响应Sample response

        "displaySource": "elephants",
        "normalizedSource": "elephants",
        "translations": [
                "backTranslations": [
                        "displayText": "elephants",
                        "frequencyCount": 1207,
                        "normalizedText": "elephants",
                        "numExamples": 5
                "confidence": 1.0,
                "displayTarget": "elefantes",
                "normalizedTarget": "elefantes",
                "posTag": "NOUN",
                "prefixWord": ""

清理资源Clean up resources

如果已将订阅密钥硬编码到程序中,请确保在完成本快速入门后删除该订阅密钥。If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

后续步骤Next steps

查看 API 参考,了解使用文本翻译 API 可以执行的所有操作。Take a look at the API reference to understand everything you can do with the Translator Text API.

另请参阅See also

了解如何使用文本翻译 API 执行以下操作:Learn how to use the Translator Text API to: