import java.util.logging.Logger;
import edu.stanford.nlp.ie.crf.CRFClassifier;
-import edu.stanford.nlp.ling.CoreAnnotations.AnswerAnnotation;
-import edu.stanford.nlp.ling.CoreLabel;
+import edu.stanford.nlp.util.CoreMap;
+import edu.stanford.nlp.util.Triple;
+import pnews.servlet.Config;
/** https://stanfordnlp.github.io/CoreNLP/api.html */
public class NER {
private static final String CLASS_NAME = NER.class.getName();
- private static final Logger LOG = Logger.getLogger(CLASS_NAME);
+ private static final Logger LOG = Logger.getLogger(CLASS_NAME);
+ private static final CRFClassifier<CoreMap> classifier = CRFClassifier.getDefaultClassifier();
- public static List<String> classify(String str, List<String> entities) throws ClassCastException, ClassNotFoundException, IOException {
- CRFClassifier<CoreLabel> classifier;
- List<List<CoreLabel>> out;
- String cat, w;
- final String FUNCTION_NAME = "classify";
+ public static List<String> classify(String str, List<String> entities, Config config) throws ClassCastException, ClassNotFoundException, IOException {
+
+ List<Triple<String, Integer, Integer>> triples;
+ String w;
+ final String FUNCTION_NAME = "classify";
LOG.entering(CLASS_NAME, FUNCTION_NAME, str);
- OpenNLP.classify(str, entities);
-
- classifier = CRFClassifier.getDefaultClassifier();
- out = classifier.classify(str);
-
- for (List<CoreLabel> labels: out)
- for (CoreLabel l: labels) {
- cat = l.getString(AnswerAnnotation.class);
- w = l.word();
- if (!cat.equals("O") && !entities.contains(w))
- entities.add(w);
- }
-
- entities.remove("CNET");
- entities.remove("Read More");
- entities.remove("New");
- entities.remove("App");
+ OpenNLP.classify(str, entities, config);
+
+ synchronized (classifier) {
+ triples = classifier.classifyToCharacterOffsets(str);
+ }
+
+ for (Triple<String, Integer, Integer> t: triples) {
+ w = str.substring(t.second, t.third);
+ if (!config.isBlacklistedEntity(w) && !entities.contains(w))
+ entities.add(config.getEntityAlias(w));
+ }
LOG.exiting(CLASS_NAME, FUNCTION_NAME, entities);
}
public static void main(String[] args) throws Exception {
- classify("I live in Washington.", new ArrayList<>());
+ List<String> lst;
+
+ lst = classify("I live in Washington and New York in United States.", new ArrayList<>(), new Config());
+ for (String str: lst)
+ System.out.println(str);
}
}
\ No newline at end of file