未找到 Stanford CoreNLP 属性文件

Stanford CoreNLP properties File not found

我正在尝试对推文进行情绪分析,但出现了奇怪的异常。

我正在使用属性文件初始化管道,并将属性文件放在 src->main 文件夹内的资源目录中。

但在初始化函数中仍然出现异常:

Exception in thread "main" edu.stanford.nlp.io.RuntimeIOException:    java.io.IOException: Unable to open "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz" as class path, filename or URL
at edu.stanford.nlp.parser.common.ParserGrammar.loadModel(ParserGrammar.java:188)
at edu.stanford.nlp.pipeline.ParserAnnotator.loadModel(ParserAnnotator.java:212)
at edu.stanford.nlp.pipeline.ParserAnnotator.<init>(ParserAnnotator.java:115)
at edu.stanford.nlp.pipeline.AnnotatorImplementations.parse(AnnotatorImplementations.java:150)
at edu.stanford.nlp.pipeline.AnnotatorFactories.create(AnnotatorFactories.java:463)
at edu.stanford.nlp.pipeline.AnnotatorPool.get(AnnotatorPool.java:85)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.construct(StanfordCoreNLP.java:375)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:139)
at edu.stanford.nlp.pipeline.StanfordCoreNLP.<init>(StanfordCoreNLP.java:135)
at com.mycompany.sentmentanalysisontweets.NLP.init(NLP.java:27)
at com.mycompany.sentmentanalysisontweets.WhatToThink.main(WhatToThink.java:15)

在主要方法中,我正在调用 init() 方法。

public class Main {

    public static void main(String[] args) {
        NLP.init();
    }
}

class NLP {
    static StanfordCoreNLP pipeline;

    public static void init() {
        InputStream input = NLP.class.getClass().getResourceAsStream("/example.properties");
        Properties prop = new Properties();
        try {
          prop.load(input);
        } catch (IOException e) {
          e.printStackTrace();
        }

        pipeline = new StanfordCoreNLP(prop);
    }
}

具有以下结构:

src/main/resources
             |
              - example.properties

执行下面的代码将解决您的问题:

public class Main {

    public static void main(String[] args) {
        NLP.init();
    }
}

class NLP {
   static StanfordCoreNLP pipeline;

   public static void init() {
        InputStream input = NLP.class.getClass().getResourceAsStream("/example.properties");
        Properties prop = new Properties();
        try {
            prop.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }

        pipeline = new StanfordCoreNLP(prop);
    }
}

编辑

您的 pom.xml 必须包含以下依赖项:

<dependencies>
    <dependency>
        <groupId>edu.stanford.nlp</groupId>
        <artifactId>stanford-corenlp</artifactId>
        <version>3.6.0</version>
    </dependency>
    <dependency>
        <groupId>edu.stanford.nlp</groupId>
        <artifactId>stanford-corenlp</artifactId>
        <version>3.6.0</version>
        <classifier>models</classifier>
    </dependency>
</dependencies>

使用

            InputStream input = new FileInputStream(new File("./", "example.properties"));

而不是

            InputStream input = StanfordCoreNLP.class.getClass().getResourceAsStream("/example.properties");

将解决问题