在C#中做文件内容的实体识别,核心思路是先拿到文本,再用NER工具找出其中的人名、地名、机构名等实体。下面直接看基础实现方式。

一、准备工作
我们可以使用开源的斯坦福命名实体识别器,它通过命令行或Java接口提供服务。C#这边用Process调用会更简单。先准备好模型文件,比如中文模型chinese.misc.distsim.crf.ser.gz,放到项目目录下。
二、读取文本文件
用C#自带的File类就能把txt内容读出来,注意指定编码避免乱码。
using System;
using System.IO;
using System.Text;
class FileReader
{
// 读取文本文件内容
public static string ReadTextFile(string path)
{
// 使用UTF8编码读取
return File.ReadAllText(path, Encoding.UTF8);
}
}
三、调用NER工具提取实体
这里演示通过命令行调用Stanford NER的jar包,把文本传进去并获取标注结果。实际项目中也可以用更高效的HTTP接口方式。
using System;
using System.Diagnostics;
class NerRunner
{
// 调用斯坦福NER命令行返回带标注的文本
public static string RunNer(string text, string jarPath, string modelPath)
{
// 把文本写入临时文件
string tmp = "input.txt";
File.WriteAllText(tmp, text);
Process p = new Process();
p.StartInfo.FileName = "java";
// 拼接参数:主类、模型、输入文件
p.StartInfo.Arguments = "-cp " + jarPath + " edu.stanford.nlp.ie.crf.CRFClassifier -loadClassifier " + modelPath + " -textFile " + tmp;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
}
四、解析实体结果
NER输出通常是词语加斜杠加类型的格式,比如“北京/LOC”。我们可以用简单拆分来统计人名地名。
using System;
using System.Collections.Generic;
class EntityParser
{
// 从NER输出中提取地名和人名
public static void ShowEntities(string nerOutput)
{
var locations = new List<string>();
var persons = new List<string>();
string[] tokens = nerOutput.Split(new char[] { ' ', 'n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var token in tokens)
{
// 格式为 词/类型
string[] parts = token.Split('/');
if (parts.Length == 2)
{
string word = parts[0];
string type = parts[1];
if (type == "LOC") locations.Add(word);
else if (type == "PER") persons.Add(word);
}
}
Console.WriteLine("地名:" + string.Join(",", locations));
Console.WriteLine("人名:" + string.Join(",", persons));
}
}
五、整合主流程
把上面几步串起来,就能从任意文本文件里提取出实体。
using System;
class Program
{
static void Main()
{
string filePath = "demo.txt";
string text = FileReader.ReadTextFile(filePath);
string jar = "stanford-ner.jar";
string model = "chinese.misc.distsim.crf.ser.gz";
string result = NerRunner.RunNer(text, jar, model);
EntityParser.ShowEntities(result);
}
}
小结
上面例子用外部工具完成了C#文件实体识别。如果追求性能,可以把NER包装成本地服务,用HttpClient去请求。对于英文文本,也可以直接用SharpNLP等纯C#库,省去Java依赖。