using Python.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace CloudBuilder.Topshelf.Python { public class Hanlp2 { public readonly PythonCommand python; public Hanlp2(PythonCommand python) { this.python = python; string file = python.ApplicationService.Configuration["Python:PythonFile"]!; if (!File.Exists(file)) return; string init = File.ReadAllText(file, Encoding.UTF8); using (Py.GIL()) { python.Exec(init); } } public List GetHanlpNer(string text) { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_ner_json('{text}')"); // 反序列化 if (json == "[]") return null; return JsonSerializer.Deserialize>(json); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public List> GetHanlpSrl(string text) { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_srl_json('{text}')"); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true // 忽略属性名大小写 }; // 反序列化 return JsonSerializer.Deserialize>>(json, options); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public string GetDepRoot(string text) { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_root('{text}')"); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true // 忽略属性名大小写 }; // 反序列化 return json; } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public List GetHanlpCon(string text) { if (string.IsNullOrEmpty(text) || text.Length < 3) return null; try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_con_json('{text}')"); if (json == "[]") return null; return HanlpConstituencyNode.FromJsonString(json); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public List GetTokFine(string text) { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_tok_fine('{text}')"); // 反序列化 if (json == "[]") return null; return JsonSerializer.Deserialize>(json); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public List GetTokCoarse(string text) { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_tok_coarse('{text}')"); // 反序列化 if (json == "[]") return null; return JsonSerializer.Deserialize>(json); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public List GetSurnames() { try { //必须定义方法的方式使用 using (Py.GIL()) { string json = python.GetValueExec($"processor.get_surnames_json()"); // 反序列化 if (json == "[]") return null; return JsonSerializer.Deserialize>(json); } } catch (Exception ex) { Console.WriteLine(ex.Message); } return null; } public string Get(string arg) { return python.GetValueExec(arg); } } }