Before reading this article, please go through the articles, mentioned below.
- Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
- 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.
- Windows 10 (Recommended).
- Visual Studio 2015 Community Edition (It is a free software available online).
- 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.
After choosing the Target and minimum platform version for your Windows, Universal Application will support. The Project creates App.xaml and MainPage.xaml.
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.
For adding Newtonsoft.Json Reference, choose browse and search Newtonsoft.Json. Select the package and install it.
Reference is added to your project.
Step 3
Add a TextBlock control, change the Name and text property for Title.
Add a TextBlock control, change the name and set the sample text in the text property for Linguistics POS tags.
Add a Button control, set the name and add the Edit icon for Linguistics POS tags.
Step 4
Add GridView Resources, using the code, mentioned below.
- <Grid.Resources>
- <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">
Add the code, mentioned below for Grid View Item Template for Phrase list.
- <GridView.ItemTemplate>
- <DataTemplate>
- <Border Background="AliceBlue" Width="497" Height="257" Margin="8">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="auto" />
- <ColumnDefinition/> </Grid.ColumnDefinitions>
- <Grid Grid.Column="1" Margin="3,3,3,10">
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" /> </Grid.RowDefinitions>
- <StackPanel Margin="0,0,0,-220">
- <TextBlock TextWrapping="Wrap" Text="{Binding ltco.AnalyzerId}" Style="{StaticResource CaptionTextBlockStyle}" Height="32" FontSize="16" />
- <TextBlock TextWrapping="Wrap" Text="{Binding ltco.Tags}" Style="{StaticResource CaptionTextBlockStyle}" Height="199" FontSize="16" /> </StackPanel>
- </Grid>
- </Grid>
- </Border>
- </DataTemplate>
- </GridView.ItemTemplate>
Step 5
Add a TextBlock control with HyperLink tag and set the link for POS tags.
Step 6
Add the Click event method for the button control.
Note
Automatically, the code mentioned below will be generated in XAML code view, while we are done in the design view.
- <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">
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <Grid.Resources>
- <CollectionViewSource x:Name="SenTagCol" Source="{x:Bind TagResults}" IsSourceGrouped="False" /> </Grid.Resources>
- <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" />
- <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" />
- <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" />
- <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">
- <SymbolIcon Symbol="Find"></SymbolIcon>
- </Button>
- <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">
- <GridView.ItemTemplate>
- <DataTemplate>
- <Border Background="AliceBlue" Width="497" Height="257" Margin="8">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="auto" />
- <ColumnDefinition/> </Grid.ColumnDefinitions>
- <Grid Grid.Column="1" Margin="3,3,3,10">
- <Grid.RowDefinitions>
- <RowDefinition Height="auto" /> </Grid.RowDefinitions>
- <StackPanel Margin="0,0,0,-220">
- <TextBlock TextWrapping="Wrap" Text="{Binding ltco.AnalyzerId}" Style="{StaticResource CaptionTextBlockStyle}" Height="32" FontSize="16" />
- <TextBlock TextWrapping="Wrap" Text="{Binding ltco.Tags}" Style="{StaticResource CaptionTextBlockStyle}" Height="199" FontSize="16" /> </StackPanel>
- </Grid>
- </Grid>
- </Border>
- </DataTemplate>
- </GridView.ItemTemplate>
- </GridView>
- <TextBlock x:Name="tbl_Link" HorizontalAlignment="Left" Margin="145,553,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="29" Width="1014">
- <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>
- </TextBlock>
- </Grid>
- </Page>
Step 7
Add the namespaces, mentioned below in Mainpage.xaml.cs for POS tags.
- using System.Net.Http;
- using System.Threading.Tasks;
- using Newtonsoft.Json.Linq;
- using System.Collections.ObjectModel;
- using System.Net.Http.Headers;
- 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,
- public class Ling {
- public string AnalyzerId {
- get;
- set;
- }
- public string Tags {
- get;
- set;
- }
- }
- public class LingCol {
- public Ling ltco {
- get;
- set;
- }
- }
- static string requestString;
- public ObservableCollection < LingCol > TagResults {
- get;
- set;
- } = new ObservableCollection < LingCol > ();
- private async void btnTag_Click(object sender, RoutedEventArgs e) {
- var la = await serparateTags();
- for (int i = 0; i < la.Count(); i++) {
- Ling ltc = la.ElementAt(i);
- TagResults.Add(new LingCol {
- ltco = ltc
- });
- }
- }
- static async Task < IEnumerable < Ling >> serparateTags() {
- List < Ling > lingli = new List < Ling > ();
- var client = new HttpClient();
- requestString = "{ \"language\" : \"en\",";
- requestString += "\"analyzerIds\" : [\" 4fa79af1-f22c-408d-98bb-b7d7aeef7f04\", \"22a6b758-420f-4745-8a3c-46835a67c0d2\"], ";
- requestString += "\"text\" : \"Welcome to C Sharp Corner!.\" }";
- client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<Your Key>");
- var uri = "https://api.projectoxford.ai/linguistics/v1.0/analyze?";
- HttpResponseMessage response;
- byte[] byteData = Encoding.UTF8.GetBytes(requestString);
- using(var content = new ByteArrayContent(byteData)) {
- content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
- response = await client.PostAsync(uri, content);
- }
- var json = await response.Content.ReadAsStringAsync();
- var data = JArray.Parse(json);
- foreach(JObject root in data) {
- JArray sizes = (JArray) root["result"];
- string[] id = new string[50];
- for (int i = 0; i < sizes.Count; i++) {
- id[i] = (string) sizes[i].ToString();
- }
- lingli.Add(new Ling {
- AnalyzerId = "Analyzer Id : " + (String) root["analyzerId"],
- Tags = "Tags : " + id[0]
- });
- }
- return lingli;
- }
Step 9
Deploy your app in Local Machine and the output of UWPCogSerLing app is shown below.
After clicking the Button
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.