Finding POS Tags In A Sentence Using Cognitive Service Linguistic Analysis API

Before reading this article, please go through the articles, mentioned below.

  1. Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
  2. Cognitive Service Linguistic Analysis API

Microsoft Cognitive Services (formerly Project Oxford) is a set of API's, SDK's and Services available to the developers to make their applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning APIs and enables developers to easily add intelligent features. Microsoft Cognitive Services let you build apps with powerful algorithms using just a few lines of code. They work across devices and platforms such as iOS, Android, and Windows, keep improving, and are easy to set up.

Linguistic Analysis APIs

Provide access to natural language processing (NLP) tools that identifies the structure of the text. The current release provides three types of analysis: Sentence separation and tokenization, Part-of-speech tagging, Constituency parsing.

Part-of-Speech (POS) Tags Response

The output is the list of lists of strings. For each sentence, there is a list of POS tags, one POS tag for each token. To find the token corresponding to each POS tag, you want to ask for a tokenization object as well.

By reading this article, you can learn how to find POS tags in a sentence, using Cognitive Service Linguistic Analysis API, Universal Windows Apps development with XAML and Visual C#.

The important tools, mentioned below are required to develop UWP.

  1. Windows 10 (Recommended).
  2. Visual Studio 2015 Community Edition (It is a free software available online).
  3. Cognitive Service Linguistic Analysis API Key (Refer the link Microsoft Cognitive Services API's and click the link Get started for free).

Now, we can discuss step by step app development.

Step 1

Open Visual Studio 2015 -> Start -> New Project-> Select Universal (under Visual C#->Windows)-> Blank app -> Give the suitable name for your app (UWPCogSerLing)->OK.

Microsoft

After choosing the Target and minimum platform version for your Windows, Universal Application will support. The Project creates App.xaml and MainPage.xaml.

Microsoft

Step 2

Open (double click) the file MainPage.xaml in Solution Explorer and add the Newtonsoft.Json reference in the project. Right click your Project (UWPCogSerLing) and select Manage NuGet Packages.

Microsoft

For adding Newtonsoft.Json Reference, choose browse and search Newtonsoft.Json. Select the package and install it.

Microsoft

Reference is added to your project.

Microsoft
Step 3

Add a TextBlock control, change the Name and text property for Title.

Microsoft

Add a TextBlock control, change the name and set the sample text in the text property for Linguistics POS tags.

Microsoft

Add a Button control, set the name and add the Edit icon for Linguistics POS tags.

Microsoft

Step 4

Add GridView Resources, using the code, mentioned below.

  1. <Grid.Resources>  
  2.     <CollectionViewSource x:Name="SenTagCol" Source="{x:Bind TagResults}" IsSourceGrouped="False" /> </Grid.Resources Add a GridView Control and set the ItemSource properties <GridView x:Name="gvTags" ItemsSource="{Binding Source={StaticResource SenTagCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="98,272,0,0" VerticalAlignment="Top" Width="1061">// This is just a sample script. Paste your real code (javascript or HTML) here. if ('this_is'==/an_example/){of_beautifier();}else{var a=b?(c%d):e[f];}  
Microsoft

Add the code, mentioned below for Grid View Item Template for Phrase list.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="AliceBlue" Width="497" Height="257" Margin="8">  
  4.             <Grid>  
  5.                 <Grid.ColumnDefinitions>  
  6.                     <ColumnDefinition Width="auto" />  
  7.                     <ColumnDefinition/> </Grid.ColumnDefinitions>  
  8.                 <Grid Grid.Column="1" Margin="3,3,3,10">  
  9.                     <Grid.RowDefinitions>  
  10.                         <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  11.                     <StackPanel Margin="0,0,0,-220">  
  12.                         <TextBlock TextWrapping="Wrap" Text="{Binding ltco.AnalyzerId}" Style="{StaticResource CaptionTextBlockStyle}" Height="32" FontSize="16" />  
  13.                         <TextBlock TextWrapping="Wrap" Text="{Binding ltco.Tags}" Style="{StaticResource CaptionTextBlockStyle}" Height="199" FontSize="16" /> </StackPanel>  
  14.                 </Grid>  
  15.             </Grid>  
  16.         </Border>  
  17.     </DataTemplate>  
  18. </GridView.ItemTemplate>  
Microsoft

Step 5

Add a TextBlock control with HyperLink tag and set the link for POS tags.

Microsoft

Step 6

Add the Click event method for the button control.

Microsoft

Note

Automatically, the code mentioned below will be generated in XAML code view, while we are done in the design view.
  1. <Page x:Class="UWPCogSerLing.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPCogSerLing" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">  
  2.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  3.         <Grid.Resources>  
  4.             <CollectionViewSource x:Name="SenTagCol" Source="{x:Bind TagResults}" IsSourceGrouped="False" /> </Grid.Resources>  
  5.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="197,134,0,0" TextWrapping="Wrap" Text="UWP - Finding POS Tags in a Sentence Using Coginitive Service Linguistic Analysis API " VerticalAlignment="Top" FontWeight="Bold" FontSize="22" Width="982" />  
  6.         <TextBlock x:Name="tblsamp" HorizontalAlignment="Left" Margin="333,212,0,0" TextWrapping="Wrap" Text="Sample Sentence : " VerticalAlignment="Top" Height="28" Width="175" FontWeight="Bold" FontSize="18" />  
  7.         <TextBlock x:Name="tblText" HorizontalAlignment="Left" Margin="533,212,0,0" TextWrapping="Wrap" Text="Welcome to C Sharp Corner!." VerticalAlignment="Top" FontSize="20" Height="28" Width="294" />  
  8.         <Button x:Name="btnTag" HorizontalAlignment="Left" Margin="856,215,0,0" VerticalAlignment="Top" RenderTransformOrigin="3.6,0.312" ToolTipService.ToolTip="Click to Find The Tags" Click="btnTag_Click">  
  9. <SymbolIcon Symbol="Find"></SymbolIcon>  
  10. </Button>  
  11.         <GridView x:Name="gvTags" ItemsSource="{Binding Source={StaticResource SenTagCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="98,272,0,0" VerticalAlignment="Top" Width="1061">  
  12.             <GridView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.                     <Border Background="AliceBlue" Width="497" Height="257" Margin="8">  
  15.                         <Grid>  
  16.                             <Grid.ColumnDefinitions>  
  17.                                 <ColumnDefinition Width="auto" />  
  18.                                 <ColumnDefinition/> </Grid.ColumnDefinitions>  
  19.                             <Grid Grid.Column="1" Margin="3,3,3,10">  
  20.                                 <Grid.RowDefinitions>  
  21.                                     <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  22.                                 <StackPanel Margin="0,0,0,-220">  
  23.                                     <TextBlock TextWrapping="Wrap" Text="{Binding ltco.AnalyzerId}" Style="{StaticResource CaptionTextBlockStyle}" Height="32" FontSize="16" />  
  24.                                     <TextBlock TextWrapping="Wrap" Text="{Binding ltco.Tags}" Style="{StaticResource CaptionTextBlockStyle}" Height="199" FontSize="16" /> </StackPanel>  
  25.                             </Grid>  
  26.                         </Grid>  
  27.                     </Border>  
  28.                 </DataTemplate>  
  29.             </GridView.ItemTemplate>  
  30.         </GridView>  
  31.         <TextBlock x:Name="tbl_Link" HorizontalAlignment="Left" Margin="145,553,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="29" Width="1014">  
  32.             <Hyperlink NavigateUri="https://www.microsoft.com/cognitive-services/en-us/Linguistic-Analysis-API/documentation/POS-tagging"> Please Click Here for Expansion of Tags, Ex. NNP - noun, proper, singular </Hyperlink>  
  33.         </TextBlock>  
  34.     </Grid>  
  35. </Page>  
Step 7

Add the namespaces, mentioned below in Mainpage.xaml.cs for POS tags.
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Newtonsoft.Json.Linq;  
  4. using System.Collections.ObjectModel;  
  5. using System.Net.Http.Headers;  
  6. using System.Text;  
Step 8

Add the 'Using Cognitive Service Linguistic Analysis API Client keys' to use the link Microsoft Cognitive Services APIs and click the link Get started for free for Trial)

Linguistic Analysis API- POS Tags Analyze Request URL and Analyzer ID's.

https://api.projectoxford.ai/linguistics/v1.0/analyze

analyzerIds : 4fa79af1-f22c-408d-98bb-b7d7aeef7f04, 22a6b758-420f-4745-8a3c-46835a67c0d2


Add the code, mentioned below with Azure generated key for POS Tags Analyze in a sentence,
  1. public class Ling {  
  2.     public string AnalyzerId {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Tags {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
  11. public class LingCol {  
  12.     public Ling ltco {  
  13.         get;  
  14.         set;  
  15.     }  
  16. }  
  17. static string requestString;  
  18. public ObservableCollection < LingCol > TagResults {  
  19.     get;  
  20.     set;  
  21. } = new ObservableCollection < LingCol > ();  
  22. private async void btnTag_Click(object sender, RoutedEventArgs e) {  
  23.     var la = await serparateTags();  
  24.     for (int i = 0; i < la.Count(); i++) {  
  25.         Ling ltc = la.ElementAt(i);  
  26.         TagResults.Add(new LingCol {  
  27.             ltco = ltc  
  28.         });  
  29.     }  
  30. }  
  31. static async Task < IEnumerable < Ling >> serparateTags() {  
  32.     List < Ling > lingli = new List < Ling > ();  
  33.     var client = new HttpClient();  
  34.     requestString = "{ \"language\" : \"en\",";  
  35.     requestString += "\"analyzerIds\" : [\" 4fa79af1-f22c-408d-98bb-b7d7aeef7f04\", \"22a6b758-420f-4745-8a3c-46835a67c0d2\"], ";  
  36.     requestString += "\"text\" : \"Welcome to C Sharp Corner!.\" }";  
  37.     client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  38.     var uri = "https://api.projectoxford.ai/linguistics/v1.0/analyze?";  
  39.     HttpResponseMessage response;  
  40.     byte[] byteData = Encoding.UTF8.GetBytes(requestString);  
  41.     using(var content = new ByteArrayContent(byteData)) {  
  42.         content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  43.         response = await client.PostAsync(uri, content);  
  44.     }  
  45.     var json = await response.Content.ReadAsStringAsync();  
  46.     var data = JArray.Parse(json); // parse as array  
  47.     foreach(JObject root in data) {  
  48.         JArray sizes = (JArray) root["result"];  
  49.         string[] id = new string[50];  
  50.         for (int i = 0; i < sizes.Count; i++) {  
  51.             id[i] = (string) sizes[i].ToString();  
  52.         }  
  53.         lingli.Add(new Ling {  
  54.             AnalyzerId = "Analyzer Id : " + (String) root["analyzerId"],  
  55.                 Tags = "Tags : " + id[0]  
  56.         });  
  57.     }  
  58.     return lingli;  
  59. }  

Microsoft

Step 9

Deploy your app in Local Machine and the output of UWPCogSerLing app is shown below.
Microsoft

After clicking the Button

Microsoft

Summary

Now, you have successfully retrieved the POS tags from the given text, using Linguistic Analysis API - POS Tags Analyze, Azure, XAML AND C# with UWP environment.

Up Next
    Ebook Download
    View all
    Learn
    View all