快速入门:使用 Python 通过文本翻译 API 获取所支持语言的列表Quickstart: Use the Translator Text API to get a list of supported languages using Python

本快速入门介绍如何使用 Python 和文本翻译 REST API 发出可以返回所支持语言的列表的 GET 请求。In this quickstart, you'll learn how to make a GET request that returns a list of supported languages using Python and the Translator Text REST API.

提示

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

先决条件Prerequisites

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

  • Python 2.7.x 或 3.xPython 2.7.x or 3.x

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

使用最喜欢的 IDE 或编辑器创建新的 Python 项目。Create a new Python project using your favorite IDE or editor. 然后,将此代码片段复制到项目的名为 get-languages.py 的文件中。Then copy this code snippet into your project in a file named get-languages.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 base url, and path

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

备注

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

base_url = 'https://api.translator.azure.cn'
path = '/languages?api-version=3.0'
constructed_url = base_url + path

添加标头Add headers

请求获取支持的语言不需身份验证。The request to get supported languages doesn't require authentication. Content-type 设置为 application/json 并添加 X-ClientTraceId,以便对请求进行唯一标识。Set the Content-type as application/json and add X-ClientTraceId to uniquely identify your request.

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

headers = {
    '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 get a list of supported languages

请使用 requests 模块创建 GET 请求。Let's create a GET request using the requests module. 它使用两个参数:串联的 URL 和请求标头:It takes two arguments: the concatenated URL, and the request headers:

request = requests.get(constructed_url, headers=headers)
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 get-languages.py

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

示例响应Sample response

请在此语言列表中查找国家/地区缩写。Find the country/region abbreviation in this list of languages.

此示例已截断,显示了结果的片段:This sample has been truncated to show a snippet of the result:

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

清理资源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: