首页 文章

如何从dotnet连接Stanford Core Server

提问于
浏览
0

我正在尝试使用Stanford NLP for .NET . 我对此很新 .

如何从c#程序连接Stanford核心NLP服务器

我的NLP服务器在localhost:9000上运行

1 回答

  • 0

    您可以通过.NET HTTPClient或其他等效的.NET调用连接到Web endpoints . 您需要设置NLP endpoints ,NLP服务器的属性以及要分析的文本内容 . 有关Stanford NLP Server page的其他信息,以及根据您要运行的NLP管道可以设置哪些属性的信息 .

    以下代码来自 .NET Core console application ,使用以下调用返回命名实体识别,依赖性分析器和OpenIE结果 .

    当我从睡眠模式唤醒笔记本电脑时(在Win10上使用Docker for Windows 17.12之前),我可以正常工作 . 重置Docker为我做了诀窍......如果你无法浏览到你的http://localhost:9000网站,那么 endpoints 肯定也无法正常工作!

    using System.Collections.Generic;
        using System.Threading.Tasks;
        using System.Net.Http;
    
        // String to process
        string s = "This is the sentence to provide to NLP."
    
        // Set up the endpoint
        string nlpBaseAddress = "http://localhost:9000"
    
        // Create the query string params for NLPCore
        string jsonOptions = "{\"annotators\": \"ner, depparse, openie\", \"outputformat\": \"json\"}";
        Dictionary qstringProperties = new Dictionary();
        qstringProperties.Add("properties", jsonOptions);
        string qString = ToQueryString(qstringProperties);
    
        // Add the query string to the base address
        string urlPlusQuery = nlpBaseAddress + qString;
    
        // Create the content to submit
        var content = new StringContent(s);
        content.Headers.Clear();
        content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
    
        // Submit for processing
        var client = new HttpClient();
    
        HttpResponseMessage response;
        Task tResponse = client.PostAsync(urlPlusQuery, content);
        tResponse.Wait();
        response = tResponse.Result;
    
        // Check the response
        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
           // Do something better than throwing an app exception here!
           throw new ApplicationException("Subject-Object tuple extraction returned an unexpected response from the subject-object service");
        }
    
        Task rString = response.Content.ReadAsStringAsync();
        rString.Wait();
        string jsonResult = rString.Result;
    

    在此调用中使用的实用程序函数生成QueryString:

    private string ToQueryString(Dictionary nvc)
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder("?");
    
                    bool first = true;
    
                    foreach (KeyValuePair key in nvc)
                    {
                        // CHeck if this is the first value
                        if (!first)
                        {
                            sb.Append("&");
                        }
    
                        sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key.Key), Uri.EscapeDataString(key.Value));
    
                        first = false;
                    }
    
                    return sb.ToString();
                }
    

相关问题