Stanford nlp for python

前端 未结 9 1248
野的像风
野的像风 2020-11-29 17:41

All I want to do is find the sentiment (positive/negative/neutral) of any given string. On researching I came across Stanford NLP. But sadly its in Java. Any ideas on how ca

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 18:31

    I also faced similar situation. Most of my projects are in Python and sentiment part is Java. Luckily it's quite easy to lean how to use the stanford CoreNLP jar.

    Here is one of my scripts and you can download jars and run it.

    import java.util.List;
    import java.util.Properties;
    import edu.stanford.nlp.ling.CoreAnnotations;
    import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
    import edu.stanford.nlp.pipeline.Annotation;
    import edu.stanford.nlp.pipeline.StanfordCoreNLP;
    import edu.stanford.nlp.sentiment.SentimentCoreAnnotations.SentimentAnnotatedTree;
    import edu.stanford.nlp.trees.Tree;
    import edu.stanford.nlp.util.ArrayCoreMap;
    import edu.stanford.nlp.util.CoreMap;
    
    public class Simple_NLP {
    static StanfordCoreNLP pipeline;
    
        public static void init() {
            Properties props = new Properties();
            props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
            pipeline = new StanfordCoreNLP(props);
        }
    
        public static String findSentiment(String tweet) {
            String SentiReturn = "";
            String[] SentiClass ={"very negative", "negative", "neutral", "positive", "very positive"};
    
            //Sentiment is an integer, ranging from 0 to 4. 
            //0 is very negative, 1 negative, 2 neutral, 3 positive and 4 very positive.
            int sentiment = 2;
    
            if (tweet != null && tweet.length() > 0) {
                Annotation annotation = pipeline.process(tweet);
    
                List sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
                if (sentences != null && sentences.size() > 0) {
    
                    ArrayCoreMap sentence = (ArrayCoreMap) sentences.get(0);                
                    Tree tree = sentence.get(SentimentAnnotatedTree.class);  
                    sentiment = RNNCoreAnnotations.getPredictedClass(tree);             
                    SentiReturn = SentiClass[sentiment];
                }
            }
            return SentiReturn;
        }
    
    }
    

提交回复
热议问题