您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

快速入门:使用文本翻译 API 通过 Python 对文本进行直译Quickstart: Use the Translator Text API to transliterate text using Python

本快速入门介绍如何使用 Python 和文本翻译 REST API 将文本从一个脚本直译(转换)为另一个脚本。In this quickstart, you'll learn how to transliterate (convert) text from one script to another using Python and the Translator Text REST API. 在提供的示例中,日语在经过直译后使用拉丁字母。In the sample provided, Japanese is transliterated to use the Latin alphabet.

此快速入门需要包含文本翻译资源的 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 free trial to get a subscription key.


本快速入门需要: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 或编辑器创建一个新项目,或者在桌面上创建一个包含名为 transliterate-text.py 的文件的新文件夹。Create a new project using your favorite IDE or editor, or a new folder with a file named transliterate-text.py on your desktop. 然后将以下代码片段复制到项目/文件中:Then copy this code snippet into your project/file:

# -*- coding: utf-8 -*-
import os, requests, uuid, 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.
#subscriptionKey = 'put_your_key_here'

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

params 用于设置输入语言以及输入和输出脚本。The params are used to set the input language, and the input and output scripts. 在此示例中,我们从日语直译为拉丁字母。In this sample, we're transliterating from Japanese to the Latin alphabet.


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

base_url = 'https://api.cognitive.microsofttranslator.com'
path = '/transliterate?api-version=3.0'
params = '&language=ja&fromScript=jpan&toScript=latn'
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,
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())

创建文本直译请求Create a request to transliterate text

定义要直译的字符串:Define the string (or strings) that you want to transliterate:

# Transliterate "good afternoon" from source Japanese.
# Note: You can pass more than one object in body.
body = [{
    'text': 'こんにちは'

接下来,请使用 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 transliterate-text.py

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

示例响应Sample response

        "script": "latn",
        "text": "konnichiwa"

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

另请参阅See also

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