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

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

本快速入门介绍如何使用 .NET Core (C#) 和文本翻译 REST API 将文本从一个脚本直译(转换)为另一个脚本。In this quickstart, you'll learn how to transliterate (convert) text from one script to another using .NET Core (C#) 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.

先决条件Prerequisites

创建 .NET Core 项目Create a .NET Core project

打开新的命令提示符(或终端会话)并运行以下命令:Open a new command prompt (or terminal session) and run these commands:

dotnet new console -o transliterate-sample
cd transliterate-sample

第一个命令执行两项操作。The first command does two things. 它创建新的 .NET 控制台应用程序,并创建名为 transliterate-sample 的目录。It creates a new .NET console application, and creates a directory named transliterate-sample. 第二个目录转到项目的目录。The second command changes to the directory for your project.

接下来需安装 Json.Net。Next, you'll need to install Json.Net. 在项目的目录中,运行以下命令:From your project's directory, run:

dotnet add package Newtonsoft.Json --version 11.0.2

将所需命名空间添加到项目Add required namespaces to your project

此前运行的 dotnet new console 命令创建了一个项目(包括 Program.cs)。The dotnet new console command that you ran earlier created a project, including Program.cs. 此文件是需放置应用程序代码的位置。This file is where you'll put your application code. 打开 Program.cs,替换现有的 using 语句。Open Program.cs, and replace the existing using statements. 这些语句可确保你有权访问生成并运行示例应用所需的所有类型。These statements ensure that you have access to all the types required to build and run the sample app.

using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

创建文本直译函数Create a function to transliterate text

Program 类中创建名为 TransliterateText 的函数。Within the Program class, create a function called TransliterateText. 该类封装用于调用 Transliterate 资源的代码,并将结果输出到控制台。This class encapsulates the code used to call the Transliterate resource and prints the result to console.

static void TransliterateText()
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

设置订阅密钥、主机名称和路径Set the subscription key, host name, and path

将以下行添加到 TransliterateText 函数。Add these lines to the TransliterateText function. 你会注意到,除了 api-version,还有两个参数已追加到 routeYou'll notice that along with the api-version, two additional parameters have been appended to the route. 这些参数用于设置输入语言和直译脚本。These parameters are used to set the input language, and the scripts for transliteration. 在此示例中,它设置为日语 (jpan) 和拉丁文 (latn)。In this sample, it's set to Japanese (jpan) and Latin (latn). 确保更新订阅密钥值。Make sure you update the subscription key value.

string host = "https://api.cognitive.microsofttranslator.com";
string route = "/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn";
string subscriptionKey = "YOUR_SUBSCRIPTION_KEY";

接下来需创建 JSON 对象并将其序列化,其中包含要直译的文本。Next, we need to create and serialize the JSON object that includes the text you want to transliterate. 请记住,可以在 body 数组中传递多个对象。Keep in mind, you can pass more than one object in the body array.

System.Object[] body = new System.Object[] { new { Text = @"こんにちは" } };
var requestBody = JsonConvert.SerializeObject(body);

实例化客户端并发出请求Instantiate the client and make a request

以下行实例化 HttpClientHttpRequestMessageThese lines instantiate the HttpClient and the HttpRequestMessage:

using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
  // In the next few sections you'll add code to construct the request.
}

构造请求并输出响应Construct the request and print the response

HttpRequestMessage 中,需执行以下操作:Inside the HttpRequestMessage you'll:

  • 声明 HTTP 方法Declare the HTTP method
  • 构造请求 URIConstruct the request URI
  • 插入请求正文(序列化的 JSON 对象)Insert the request body (serialized JSON object)
  • 添加必需的标头Add required headers
  • 发出异步请求Make an asynchronous request
  • 输出响应Print the response

HttpRequestMessage 添加以下代码:Add this code to the HttpRequestMessage:

// Set the method to POST
request.Method = HttpMethod.Post;

// Construct the full URI
request.RequestUri = new Uri(host + route);

// Add the serialized JSON object to your request
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");

// Add the authorization header
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;

// Print the response
Console.WriteLine(jsonResponse);
Console.WriteLine("Press any key to continue.");

将其放在一起Put it all together

最后一步是在 Main 函数中调用 TransliterateText()The last step is to call TransliterateText() in the Main function. 找到 static void Main(string[] args) 并添加以下行:Locate static void Main(string[] args) and add these lines:

TransliterateText();
Console.ReadLine();

运行示例应用Run the sample app

上述操作完成后,就可以运行示例应用了。That's it, you're ready to run your sample app. 从命令行(或终端会话)导航到项目目录,然后运行以下命令:From the command line (or terminal session), navigate to your project directory and run:

dotnet run

示例响应Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

清理资源Clean up resources

请务必删除示例应用的源代码中的机密信息,例如订阅密钥。Make sure to remove any confidential information from your sample app's source code, like subscription keys.

后续步骤Next steps

浏览此快速入门的示例代码和其他内容,包括翻译和语言识别,以及 GitHub 上的其他示例文本翻译项目。Explore the sample code for this quickstart and others, including translation and language identification, as well as other sample Translator Text projects on GitHub.

另请参阅See also