Spread the love
In this tutorial we are going to see how to use the Translator Text API Sentence Breaker. The Sentence breaker is used to break text into sentences.
Prerequisites
- To run the sample code you must have an edition of Visual Studio installed.
- You will need the Json.NET NuGet package.
- You will need the .NET SDK installed in your machine
- You will need 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.
Create your Project
To create an application to translate your text follow the steps below:
- Create a .NET Core Console Application in Visual Studio 2017
- Add the JSON.net nuget package
Install-Package Newtonsoft.Json
- Add the following code under Program
static void Break() { string host = "https://api.cognitive.microsofttranslator.com"; string route = "/breaksentence?api-version=3.0&language=en"; string subscriptionKey = "enter your subscription key"; System.Object[] body = new System.Object[] { new { Text = @"How are you? I am fine. What did you do today?" } }; var requestBody = JsonConvert.SerializeObject(body); using (var client = new HttpClient()) using (var request = new HttpRequestMessage()) { request.Method = HttpMethod.Post; request.RequestUri = new Uri(host + route); request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey); var response = client.SendAsync(request).Result; var jsonResponse = response.Content.ReadAsStringAsync().Result; Console.WriteLine(jsonResponse); Console.WriteLine("Press any key to continue."); } } static void Main(string[] args) { Break(); Console.ReadLine(); } }
- Replace your subscription key here: string subscriptionKey = “enter your subscription key”;
- Add here the text you want to be translated System.Object[] body = new System.Object[] { new { Text = @”How are you? I am fine. What did you do today?” } };
- Run the Program
Get Results
The result is in the following format. That’s it, we have broken the text into sentences. The result shows us the length each sentence has.
[ { "sentenceLengths": [ 13, 11, 22 ] "detectedLanguage": { "language": "en", "score": 401 }, } ]
You can find the complete source code in my Github in this repository in the Sentence Breaker Project.