快速入门:Azure 认知服务翻译器 REST API 您所在的位置:网站首页 function造句并翻译 快速入门:Azure 认知服务翻译器 REST API

快速入门:Azure 认知服务翻译器 REST API

2023-05-22 20:44| 来源: 网络整理| 查看: 265

你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

快速入门:Azure 认知服务翻译器 REST API 项目 05/15/2023

试用最新版本的 Azure 翻译器。 在本快速入门中,开始使用翻译器服务以所选的编程语言或 REST API 翻译文本。 对于此项目,建议你在学习技术时使用免费定价层 (F0),在以后再升级到付费层进行生产。

先决条件

需要一个活动 Azure 订阅。 如果你没有 Azure 订阅,可以免费创建一个

获得 Azure 订阅后,在 Azure 门户中创建一个翻译器资源。

部署资源后,选择“转到资源”并检索密钥和终结点。

需要从资源获取密钥和终结点,以便将应用程序连接到翻译器服务。 稍后需要在本快速入门中将密钥和终结点粘贴到代码中。 可以在 Azure 门户的“密钥和终结点”页面上找到这些值:

注意

对于本快速入门,建议使用文本翻译单服务全局资源。 使用单服务全局资源,你将在 REST API 请求中包含一个授权标头 (Ocp-Apim-Subscription-key)。 Ocp-Apim-Subscription-key 的值是文本翻译订阅的 Azure 密钥。 如果选择使用多服务认知服务或区域翻译资源,则需要两个身份验证标头 (Ocp-Api-Subscription-Key 和 Ocp-Apim-Subscription-Region)。 Ocp-Apim-Subscription-Region 的值是与订阅关联的区域。 有关如何使用 Ocp-Apim-Subscription-Region 标头的详细信息,请参阅文本翻译 REST API 标头。 头文件

若要通过 REST API 调用翻译器服务,需要在每个请求中包含以下标头。 不用担心,我们会在每种编程语言的示例代码中为你包含标头。

有关翻译器身份验证选项的详细信息,请参阅翻译器 v3 参考指南。

标头 值 条件 Ocp-Apim-Subscription-Key Azure 门户中的翻译器服务密钥。 • 必需 Ocp-Apim-Subscription-Region 创建资源的区域。 •使用多服务认知服务或区域(地理)资源(如美国西部)时为必需项。·使用单服务全局翻译资源时为可选项。 Content-Type 有效负载的内容类型。 接受的值为 application/json 或 。 • 必需 Content-Length 请求正文的长度。 • 可选

重要

完成后,请记住将密钥从代码中删除,并且永远不要公开发布该密钥。 对于生产来说,请使用安全的方式存储和访问凭据,例如 Azure Key Vault。 有关详细信息,请参阅认知服务安全性一文。

翻译文本

翻译器服务的核心操作是翻译文本。 在本快速入门中,你使用所选的编程语言生成一个请求,该请求采用单个源 (from) 并提供两个输出 (to)。 然后,我们将查看一些参数,这些参数可用于调整请求和响应。

有关 Azure 翻译器服务请求限制的详细信息,请参阅文本翻译请求限制。

C#:Visual Studio Go Java:Gradle JavaScript:Node.js Python 设置 Visual Studio 项目

确保使用最新版本的 Visual Studio IDE。

提示

如果你不熟悉 Visual Studio,请尝试学习 Visual Studio 简介 Learn 模块。

打开 Visual Studio。

在“开始”页上,选择“创建新项目”。

在“创建新项目”页面上,在搜索框中输入“控制台” 。 选择“控制台应用程序”模板,然后选择“下一步” 。

在“配置新项目”对话框中,在项目名称框中输入 translator_quickstart。 将“将解决方案和项目置于同一目录中”复选框保持未选中状态,然后选择“下一步”。

在“其他信息”对话框窗口中,确保选择“.NET 6.0 (长期支持)”。 将“不使用顶级语句”复选框保持未选中状态,然后选择“创建”。

使用 NuGet 安装 Newtonsoft.json 包

右键单击“translator_quickstart”项目并选择“管理 NuGet 包...”。

选择“浏览”选项卡并键入“Newtonsoft.json”。

在右侧的包管理器窗口中选择“安装”以将该包添加到项目。

运行 C# 应用程序

注意

从 .NET 6 开始,使用 console 模板的新项目将生成与以前版本不同的新程序样式。 新的输出使用最新的 C# 功能,这些功能简化了你需要编写的代码。 使用较新版本时,只需编写 Main 方法的主体。 无需包括顶级语句、全局 using 指令或隐式 using 指令。 有关详细信息,请参阅新的 C# 模板生成顶级语句。

打开 Program.cs 文件。

删除现有的代码,包括 Console.Writeline("Hello World!") 行。 将代码示例复制并粘贴到应用程序的 Program.cs 文件中。 确保使用 Azure 门户翻译器实例中的值更新密钥变量:

using System.Text; using Newtonsoft.Json; class Program { private static readonly string key = ""; private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com"; // location, also known as region. // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page. private static readonly string location = ""; static async Task Main(string[] args) { // Input and output languages are defined as parameters. string route = "/translate?api-version=3.0&from=en&to=fr&to=zu"; string textToTranslate = "I would really like to drive your car around the block a few times!"; object[] body = new object[] { new { Text = textToTranslate } }; var requestBody = JsonConvert.SerializeObject(body); using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { // Build the request. request.Method = HttpMethod.Post; request.RequestUri = new Uri(endpoint + route); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Headers.Add("Ocp-Apim-Subscription-Key", key); // location required if you're using a multi-service or regional (not global) resource. request.Headers.Add("Ocp-Apim-Subscription-Region", location); // Send the request and get response. HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false); // Read response as a string. string result = await response.Content.ReadAsStringAsync(); Console.WriteLine(result); } } } 运行 C# 应用程序

将代码示例添加到应用程序后,选择 formRecognizer_quickstart 旁边的绿色“开始”按钮以生成和运行程序,或按 F5 键。

翻译输出:

成功调用后,应会看到以下响应:

[ { "detectedLanguage": { "language": "en", "score": 1.0 }, "translations": [ { "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!", "to": "fr" }, { "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!", "to": "zu" } ] } ] 设置 Go 环境

你可以使用任何文本编辑器来编写 Go 应用程序。 建议使用最新版本的 Visual Studio Code 和 Go 扩展。

提示

如果你不熟悉 Go,请尝试学习 Go 入门 Learn 模块。

下载并安装 Go(如果尚未这样做)。

下载适用于你的操作系统的 Go 版本。

下载完成后,运行安装程序。

打开命令提示符并输入以下命令,以确认 Go 是否已安装:

go version 生成 Go 应用程序

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建名为 "translator-app" 的新目录,并导航到该目录。

在 "translator-app" 目录中创建名为 "translation.go" 的新 GO 文件。

将提供的代码示例复制并粘贴到 "translation.go" 文件中。 确保使用 Azure 门户翻译器实例中的值更新密钥变量:

package main import ( "bytes" "encoding/json" "fmt" "log" "net/http" "net/url" ) func main() { key := "" endpoint := "https://api.cognitive.microsofttranslator.com/" uri := endpoint + "/translate?api-version=3.0" // location, also known as region. // required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page. location := "" // Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse u, _ := url.Parse(uri) q := u.Query() q.Add("from", "en") q.Add("to", "fr") q.Add("to", "zu") u.RawQuery = q.Encode() // Create an anonymous struct for your request body and encode it to JSON body := []struct { Text string }{ {Text: "I would really like to drive your car around the block a few times."}, } b, _ := json.Marshal(body) // Build the HTTP POST request req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b)) if err != nil { log.Fatal(err) } // Add required headers to the request req.Header.Add("Ocp-Apim-Subscription-Key", key) // location required if you're using a multi-service or regional (not global) resource. req.Header.Add("Ocp-Apim-Subscription-Region", location) req.Header.Add("Content-Type", "application/json") // Call the Translator API res, err := http.DefaultClient.Do(req) if err != nil { log.Fatal(err) } // Decode the JSON response var result interface{} if err := json.NewDecoder(res.Body).Decode(&result); err != nil { log.Fatal(err) } // Format and print the response to terminal prettyJSON, _ := json.MarshalIndent(result, "", " ") fmt.Printf("%s\n", prettyJSON) } 运行 Go 应用程序

将代码示例添加到应用程序后,可以在命令提示符或终端提示符下执行 Go 程序。 确保提示符的路径设置为 "translator-app" 文件夹,并使用以下命令:

go run translation.go

翻译输出:

成功调用后,应会看到以下响应:

[ { "detectedLanguage": { "language": "en", "score": 1.0 }, "translations": [ { "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!", "to": "fr" }, { "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!", "to": "zu" } ] } ] 设置 Java 环境

应使用最新版本的 Visual Studio Code 或者你首选的 IDE。 查看 Visual Studio Code 中的 Java。

提示

Visual Studio Code 提供适用于 Windows 和 macOS 的 "Java 编码包"。该编码包是 VS Code、Java 开发工具包 (JDK) 和 Microsoft 建议扩展的集合。 编码包还可用于修复现有开发环境。 如果使用 VS Code 和适用于 Java 的编码包,请安装 Gradle for Java 扩展。

如果不使用 VS Code,请确保在开发环境中安装了以下内容:

Java 开发工具包 (OpenJDK) 版本 8 或更高版本。

Gradle 版本 6.8 或更高版本。

创建新的 Gradle 项目

在控制台窗口(例如 cmd、PowerShell 或 Bash)中,为应用创建名为 "translator-text-app" 的新目录,并导航到该目录。

mkdir translator-text-app && translator-text-app mkdir translator-text-app; cd translator-text-app

从 translator-text-app 目录运行 gradle init 命令。 此命令将创建 Gradle 的基本生成文件,其中包括 build.gradle.kts - 在运行时将使用该文件创建并配置应用程序。

gradle init --type basic

当提示你选择一个 DSL 时,选择 Kotlin。

按回车键或 Enter 接受默认项目名称 (translator-text-app)。

使用以下代码更新 build.gradle.kts:

plugins { java application } application { mainClass.set("TranslatorText") } repositories { mavenCentral() } dependencies { implementation("com.squareup.okhttp3:okhttp:4.10.0") implementation("com.google.code.gson:gson:2.9.0") } 创建 Java 应用程序

从 translator-text-app 目录运行以下命令:

mkdir -p src/main/java

创建以下目录结构:

导航到 java 目录,创建一个名为 TranslatorText.java 的文件。

提示

可以使用 Powershell 创建新文件。

按住 Shift 键并右键单击该文件夹,在项目目录中打开 Powershell 窗口。

输入以下命令:New-Item TranslatorText.java。

还可以在 IDE 中创建名为 TranslatorText.java 的新文件并将其保存到 java 目录。

在 IDE 中打开 TranslatorText.java 文件,然后将以下代码示例复制并粘贴到应用程序中。 确保将密钥更新为 Azure 门户翻译器实例中的某个密钥值:

import java.io.IOException; import com.google.gson.*; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class TranslatorText { private static String key = "


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有