2、NER介绍
import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.ie.crf.CRFClassifier; import edu.stanford.nlp.ling.CoreLabel; /** * * <p> * ClassName ExtractDemo * </p> * <p> * Description 加载NER模块 * */ public class ExtractDemo { private static AbstractSequenceClassifier<CoreLabel> ner; public ExtractDemo() { InitNer(); } public void InitNer() { String serializedClassifier = "classifiers/chinese.misc.distsim.crf.ser.gz"; // chinese.misc.distsim.crf.ser.gz if (ner == null) { ner = CRFClassifier.getClassifierNoExceptions(serializedClassifier); } } public String doNer(String sent) { return ner.classifyWithInlineXML(sent); } public static void main(String args[]) { String str = "我 去 吃饭 , 告诉 李强 一声 。"; ExtractDemo extractDemo = new ExtractDemo(); System.out.println(extractDemo.doNer(str)); System.out.println("Complete!"); } }
import java.io.File; import java.io.IOException; import java.util.Properties; import org.apache.commons.io.FileUtils; import edu.stanford.nlp.ie.crf.CRFClassifier; import edu.stanford.nlp.ling.CoreLabel; /** * * <p> * Description 使用Stanford CoreNLP进行中文分词 * </p> * */ public class ZH_SegDemo { public static CRFClassifier<CoreLabel> segmenter; static { // 设置一些初始化参数 Properties props = new Properties(); props.setProperty("sighanCorporaDict", "data"); props.setProperty("serDictionary", "data/dict-chris6.ser.gz"); props.setProperty("inputEncoding", "UTF-8"); props.setProperty("sighanPostProcessing", "true"); segmenter = new CRFClassifier<CoreLabel>(props); segmenter.loadClassifierNoExceptions("data/ctb.gz", props); segmenter.flags.setProperties(props); } public static String doSegment(String sent) { String[] strs = (String[]) segmenter.segmentString(sent).toArray(); StringBuffer buf = new StringBuffer(); for (String s : strs) { buf.append(s + " "); } System.out.println("segmented res: " + buf.toString()); return buf.toString(); } public static void main(String[] args) { try { String readFileToString = FileUtils.readFileToString(new File("澳门141人食物中毒与进食“问题生蚝”有关.txt")); String doSegment = doSegment(readFileToString); System.out.println(doSegment); ExtractDemo extractDemo = new ExtractDemo(); System.out.println(extractDemo.doNer(doSegment)); System.out.println("Complete!"); } catch (IOException e) { e.printStackTrace(); } } }
注意一定是JDK 1.8+的环境,最后输出结果如下: