package org.citi.sentimentapi;
@RestController
public class SentimentController{
@Autowired
private SentimentService sv;
@RequestMapping("/sentiment/{text}")
public double apply(@PathVariable String text) throws Exception {
return sv.apply(text);
}
}
以下例外即将来临:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sentimentController': Unsatisfied dependency expressed through field 'sv'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sentimentService' defined in file [C:\Users\MG23625\Desktop\workspace\sentiment-apiImproved\target\classes\org\citi\sentimentapi\SentimentService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.citi.sentimentapi.SentimentService]: Constructor threw exception; nested exception is java.lang.NullPointerException: in must not be null
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.1.RELEASE.jar:1.5.1.RELEASE]
at org.citi.sentimentapi.Sentiment.main(Sentiment.java:11) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sentimentService' defined in file [C:\Users\MG23625\Desktop\workspace\sentiment-apiImproved\target\classes\org\citi\sentimentapi\SentimentService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.citi.sentimentapi.SentimentService]: Constructor threw exception; nested exception is java.lang.NullPointerException: in must not be null
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.citi.sentimentapi.SentimentService]: Constructor threw exception; nested exception is java.lang.NullPointerException: in must not be null
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 30 common frames omitted
Caused by: java.lang.NullPointerException: in must not be null
at java.util.Objects.requireNonNull(Objects.java:228) ~[na:1.8.0_121]
at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:194) ~[opennlp-tools-1.7.2.jar:1.7.2]
at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:173) ~[opennlp-tools-1.7.2.jar:1.7.2]
at opennlp.tools.postag.POSModel.<init>(POSModel.java:82) ~[opennlp-tools-1.7.2.jar:1.7.2]
at org.citi.sentimentapi.SentimentService$POSTagger.<init>(SentimentService.java:120) ~[classes/:na]
at org.citi.sentimentapi.SentimentService$SentimentAnalyzer.<init>(SentimentService.java:289) ~[classes/:na]
at org.citi.sentimentapi.SentimentService.<init>(SentimentService.java:388) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_121]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_121]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_121]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_121]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142) ~[spring-beans-4.3.6.RELEASE.jar:4.3.6.RELEASE]
... 32 common frames omitted
我的代码:
package org.citi.sentimentapi;
@Service
public class SentimentService {
class Word
{
public Word(String word, String pennTag)
{
if (word == null || word.isEmpty())
throw new IllegalArgumentException("word");
if (pennTag == null || pennTag.isEmpty())
throw new IllegalArgumentException("posTagInfo");
this.word = word.toLowerCase();
this.pennTag = pennTag.toUpperCase();
tag = fromPennTreebankTag(pennTag);
}
private String word;
public String getWord() {return word;}
private String pennTag;
public String getPennTag() {return pennTag;}
private String tag;
public String getTag() {return tag;}
public boolean hasTag() {return tag != null;}
String fromPennTreebankTag(String value)
{
return
value.startsWith("J") ? "a" :
value.startsWith("V") ? "v" :
value.startsWith("N") ? "n" :
value.startsWith("R") ? "r" : null;
}
@Override
public String toString()
{
return hasTag() ? word + ":" + tag : word;
}
}
abstract class Phrase
{
public Phrase(Word[] words)
{
if (words.length == 0)
throw new IllegalArgumentException();
this.words = words;
}
private Word[] words;
public Word[] getWords() {return words;}
public abstract double modifyScore(double value);
}
class Incrementer extends Phrase
{
public Incrementer(Word... words) {super(words);}
@Override
public double modifyScore(double value) {return value * 2;}
}
class Inverter extends Phrase
{
public Inverter(Word... words) {super(words);}
@Override
public double modifyScore(double value) {return value * -1;}
}
class Decrementer extends Phrase
{
public Decrementer(Word... words) {super(words);}
@Override
public double modifyScore(double value) {return value / 2;}
}
class POSTagger
{
POSTaggerME posTagger;
Tokenizer tokenizer;
SentenceDetectorME sentDetector;
public POSTagger() throws IOException
{
ClassLoader loader = getClass().getClassLoader();
//ClassLoader loader = Thread.currentThread().getContextClassLoader();
posTagger = new POSTaggerME(
new POSModel(loader.getResourceAsStream("en-pos-maxent.bin")));
tokenizer = new TokenizerME(
new TokenizerModel(loader.getResourceAsStream("en-token.bin")));
sentDetector = new SentenceDetectorME(
new SentenceModel(loader.getResourceAsStream("en-sent.bin")));
}
public Word[][] tag(String input)
{
String[] sents = sentDetector.sentDetect(input);
Word[][] res = new Word[sents.length][];
for (int i = 0; i < sents.length; i++)
{
String[] words = tokenizer.tokenize(sents[i]);
String[] tags = posTagger.tag(words);
Word[] sentence = new Word[words.length];
for (int j = 0; j < words.length; j++)
sentence[j] = new Word(words[j], tags[j]);
res[i] = sentence;
}
return res;
}
}
class WordNetLemmatizer
{
Dictionary dictionary;
public WordNetLemmatizer() throws JWNLException
{
//dictionary = Dictionary.getDefaultResourceInstance();
}
public Word getLemmatized(Word word) throws JWNLException
{
if (!word.hasTag())
return word;
IndexWord iw = dictionary.lookupIndexWord(POS.getPOSForKey(word.getTag()), word.getWord());
if (iw == null)
return word;
String lemma = iw.getLemma();
if (lemma == null || lemma.isEmpty())
return word;
return new Word(lemma, word.getPennTag());
}
}
abstract class SentimentDictionary
{
abstract double getScore(Word word);
}
class SentiWordNet extends SentimentDictionary
{
String path = "C:\\Users\\MG23625\\Downloads\\SentiWordNet_3.0.0\\home\\swn\\www\\admin\\dump\\SentiWordNet_3.0.0_20130122.txt";
Map<String, Double> dictionary;
public SentiWordNet() throws IOException
{
// This is our main dictionary representation
dictionary = new HashMap<>();
// From String to list of doubles.
HashMap<String, HashMap<Integer, Double>> tempDictionary = new HashMap<>();
try (BufferedReader csv = new BufferedReader(new FileReader(path)))
{
int lineNumber = 0;
String line;
while ((line = csv.readLine()) != null)
{
lineNumber++;
// If it's a comment, skip this line.
if (!line.trim().startsWith("#"))
{
// We use tab separation
String[] data = line.split("\t");
String wordTypeMarker = data[0];
// Example line:
// POS ID PosS NegS SynsetTerm#sensenumber Desc
// a 00009618 0.5 0.25 spartan#4 austere#3 ascetical#2
// ascetic#2 practicing great self-denial;...etc
// Is it a valid line? Otherwise, through exception.
if (data.length != 6)
{
throw new IllegalArgumentException(
"Incorrect tabulation format in file, line: " + lineNumber);
}
// Calculate synset score as score = PosS - NegS
Double synsetScore =
Double.parseDouble(data[2]) - Double.parseDouble(data[3]);
// Get all Synset terms
String[] synTermsSplit = data[4].split(" ");
// Go through all terms of current synset.
for (String synTermSplit : synTermsSplit)
{
// Get synterm and synterm rank
String[] synTermAndRank = synTermSplit.split("#");
String synTerm = synTermAndRank[0] + "#" + wordTypeMarker;
int synTermRank = Integer.parseInt(synTermAndRank[1]);
// What we get here is a map of the type:
// term -> {score of synset#1, score of synset#2...}
// Add map to term if it doesn't have one
if (!tempDictionary.containsKey(synTerm))
tempDictionary.put(synTerm, new HashMap<Integer, Double>());
// Add synset link to synterm
tempDictionary.get(synTerm).put(synTermRank, synsetScore);
}
}
}
// Go through all the terms.
for (Map.Entry<String, HashMap<Integer, Double>> entry : tempDictionary.entrySet())
{
String word = entry.getKey();
Map<Integer, Double> synSetScoreMap = entry.getValue();
// Calculate weighted average. Weigh the synsets according to
// their rank.
// Score= 1/2*first + 1/3*second + 1/4*third ..... etc.
// Sum = 1/1 + 1/2 + 1/3 ...
double score = 0.0;
double sum = 0.0;
for (Map.Entry<Integer, Double> setScore : synSetScoreMap.entrySet())
{
score += setScore.getValue() / (double) setScore.getKey();
sum += 1.0 / (double) setScore.getKey();
}
score /= sum;
dictionary.put(word, score);
}
}
}
@Override
public double getScore(Word word)
{
if (!word.hasTag())
return Double.NaN;
return dictionary.getOrDefault(word.getWord() + "#" + word.getTag(), Double.NaN);
}
}
class SentimentAnalyzer
{
Map<String, Phrase> phrases;
POSTagger posTagger;
WordNetLemmatizer lemmatizer;
SentimentDictionary sentimentDict;
public SentimentAnalyzer(SentimentDictionary dictionary) throws JWNLException, IOException
{
lemmatizer = new WordNetLemmatizer();
posTagger = new POSTagger();
sentimentDict = dictionary;
phrases = new HashMap<>();
addPhrase(new Inverter(new Word("lack", "NN"), new Word("of", "IN")));
addPhrase(new Inverter(new Word("not", "RB")));
addPhrase(new Inverter(new Word("n't", "RB")));
addPhrase(new Incrementer(new Word("too", "RB")));
addPhrase(new Incrementer(new Word("very", "RB")));
addPhrase(new Incrementer(new Word("sorely", "RB")));
addPhrase(new Decrementer(new Word("barely", "RB")));
addPhrase(new Decrementer(new Word("little", "RB")));
}
void addPhrase(Phrase value) throws JWNLException
{
phrases.put(value.getWords()[0].getWord(), value);
}
public double getScore(String input) throws JWNLException
{
double totalScore = 0;
Word[][] sentences = posTagger.tag(input);
for (Word[] sentence : sentences)
{
for (int i = 0; i < sentence.length; i++)
{
Word word = sentence[i];
Phrase p = phrases.get(word.getWord());
Phrase phrase = null;
if (p != null &&
sentence.length - i > p.getWords().length &&
containsPhrase(sentence, i, p.getWords()))
{
phrase = p;
i += phrase.getWords().length;
int j = i;
for (; j < sentence.length && !sentence[j].hasTag(); j++) ;
if (j == sentence.length)
continue;
word = sentence[j];
}
else if (!word.hasTag())
continue;
double score = sentimentDict.getScore(word);
if (Double.isNaN(score))
{
word = lemmatizer.getLemmatized(word);
score = sentimentDict.getScore(word);
}
if (!Double.isNaN(score))
{
if (phrase != null)
{
score = phrase.modifyScore(score);
//out.format("<%s> ", String.join(" ",
// stream(phrase.getWords()).map(Word::toString).toArray(String[]::new)));
}
//out.format("%s:%.2f ", word, score);
totalScore += score;
}
else
{
//out.format("%s ", word);
}
}
//out.println();
}
return totalScore;
}
boolean containsPhrase(Word[] sentence, int index, Word[] phrase)
{
if (phrase.length == 0 ||
index >= sentence.length ||
sentence.length - index < phrase.length)
{return false;}
for (int pi = 0, si = index; pi < phrase.length; pi++, si++)
{
if (sentence[si].getWord().compareTo(phrase[pi].getWord()) != 0 ||
sentence[si].getPennTag().compareTo(phrase[pi].getPennTag()) != 0)
{return false;}
}
return true;
}
}
public SentimentService() throws Exception
{
if (analyzer == null)
analyzer = new SentimentAnalyzer(new SentiWordNet());
//setCacheable(true);
}
static SentimentAnalyzer analyzer;
public double apply(String input) throws Exception
{
double score = analyzer.getScore(input);
return score;
}
}
我评论了setCacheable(true),因为它给出了一个错误。有人可以帮忙吗?
答案 0 :(得分:0)
你在第{120行POSTagger
的构造函数中获得了NPE。
Caused by: java.lang.NullPointerException: in must not be null
at java.util.Objects.requireNonNull(Objects.java:228) ~[na:1.8.0_121]
at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:194) ~[opennlp-tools-1.7.2.jar:1.7.2]
at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:173) ~[opennlp-tools-1.7.2.jar:1.7.2]
at opennlp.tools.postag.POSModel.<init>(POSModel.java:82) ~[opennlp-tools-1.7.2.jar:1.7.2]
at org.citi.sentimentapi.SentimentService$POSTagger.<init>(SentimentService.java:120) ~[classes/:na]
at org.citi.sentimentapi.SentimentService$SentimentAnalyzer.<init>(SentimentService.java:289) ~[classes/:na]
如何检查What is a NullPointerException, and how do I fix it?
但老实说,你最好重构你的代码,否则你会有很多这样的&#34;无法解决的问题&#34;未来的例外,因为它超级凌乱。
首先将类移到单独的java
文件中。