package cn.edu.bjut.chapter2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; public class SentenceSpliterByOpenNLP { private static SentenceDetectorME detector = null; private static final String MODEL_FILE = "resource/opennlp-en-ud-ewt-sentence-1.0-1.9.3.bin"; private static void loadModel(String fname) { SentenceModel model = null; try { InputStream stream = new FileInputStream(fname); try { model = new SentenceModel(stream); } catch (IOException e) { e.printStackTrace(); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } detector = new SentenceDetectorME(model); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static String[] detect(String str) { if (detector == null) { loadModel(MODEL_FILE); } return detector.sentDetect(str); } public static void main(String[] args) { String str = "Mr. Smith is here. This is a test! Isn't text mining " + "amazing? Let's see e.g. this case."; String[] sentences = detect(str); System.out.println("Sentences splitted by OpenNLP: "); for (String sentence: sentences) { System.out.println(sentence); } } }