快速入门:使用 Python 通过文本翻译 API 来确定句子长度Quickstart: Use the Translator Text API to determine sentence length using Python
07/23/2019
本文内容
本快速入门介绍如何使用 Python 和文本翻译 REST API 来确定句子长度(以字符数为单位)。In this quickstart, you'll learn how to determine sentence lengths (in characters) 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.
先决条件Prerequisites
本快速入门需要: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. 然后,将此代码片段复制到项目的名为 sentence-length.py 的文件中。Then copy this code snippet into your project in a file named sentence-length.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 uuid。To 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']
else:
print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
exit()
# 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'
region = 'put_your_region_here'
文本翻译全局终结点设置为 base_url。The Translator Text global endpoint is set as the base_url. path 设置 breaksentence 路由并确定我们需使用 API 的版本 3。path sets the breaksentence route and identifies that we want to hit version 3 of the API.
此示例中的 params 用于设置所提供文本的语言。The params in this sample are used to set the language of the provided text. params 不是 breaksentence 路由所需的。params aren't required for the breaksentence route. 如果不包含在请求中,此 API 会尝试检测所提供文本的语言,并会在响应中提供此信息以及置信度分数。If left out of the request, the API will try to detect the language of the provided text, and provide this information along with a confidence score in the response.
备注
有关终结点、路由和请求参数的详细信息,请参阅文本翻译 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 = '/breaksentence?api-version=3.0'
params = '&language=en'
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-Region。If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters.
创建一个用于确定句子长度的请求Create a request to determine sentence length
定义需要确定其长度的句子:Define the sentence (or sentences) that you want to determine the length of:
# You can pass more than one object in body.
body = [{
'text': 'How are you? I am fine. What did you do today?'
}]
接下来,请使用 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()
输出响应Print the response
最后一步是输出结果。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 sentence-length.py
如果希望将你的代码与我们的进行比较,请查看 GitHub 上提供的完整示例。If you'd like to compare your code against ours, the complete sample is available on GitHub.
示例响应Sample response
[
{
"sentLen": [
13,
11,
22
]
}
]
清理资源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: