我正在尝试使用Stanford NLP for .NET。我对此很陌生。
如何从c#program
连接Stanford核心NLP服务器我的NLP服务器在localhost:9000上运行
答案 0 :(得分:0)
您可以通过.NET HTTPClient或其他等效的.NET调用连接到Web端点。您需要设置NLP端点,NLP服务器的属性以及要分析的文本内容。有关Stanford NLP Server page的其他信息,以及根据您要运行的NLP管道可以设置哪些属性的信息。
以下代码来自 .NET Core控制台应用程序,使用以下调用返回命名实体识别,依赖关系解析器和OpenIE结果。
仅供参考我曾经在某些情况下将我的NLP端点从睡眠模式唤醒笔记本电脑时无法正常工作(Windows 10上的Docker for Windows 17.12)。重置Docker为我做了诀窍......如果你无法浏览到http://localhost:9000网站,那么端点肯定也无法工作!
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(); }