Java

如何用Java opennlp做情感分析

小樊
110
2024-07-17 20:39:46
栏目: 编程语言

OpenNLP是一个自然语言处理工具包,可以用Java编写情感分析程序。以下是一个简单的示例代码,演示如何使用OpenNLP进行情感分析:

import opennlp.tools.doccat.DoccatModel;
import opennlp.tools.doccat.DocumentCategorizerME;
import opennlp.tools.doccat.DocumentSample;
import opennlp.tools.doccat.DocumentSampleStream;
import opennlp.tools.doccat.BagOfWordsFeatureGenerator;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.TrainingParameters;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class SentimentAnalysis {

    public static void main(String[] args) throws Exception {
        // 训练模型
        InputStream dataIn = new FileInputStream(new File("data/trainData.txt"));
        ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn);
        ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);

        DoccatModel model = DocumentCategorizerME.train("en", sampleStream, new TrainingParameters(), new BagOfWordsFeatureGenerator());

        // 创建分类器
        DocumentCategorizerME categorizer = new DocumentCategorizerME(model);

        // 进行情感分析
        String[] text = {"I love this movie", "I hate this product", "It's okay"};
        for (String sentence : text) {
            double[] outcomes = categorizer.categorize(sentence);
            String category = categorizer.getBestCategory(outcomes);
            System.out.println("Sentence: " + sentence + " | Category: " + category);
        }
    }
}

在上面的示例中,我们首先从文本文件中读取训练数据,然后使用 DocumentCategorizerME.train 方法训练模型。接着创建一个 DocumentCategorizerME 分类器,并用它来对文本进行情感分析。在这个示例中,我们使用了一个包含三句话的测试集来测试分类器的性能。

请注意,这只是一个简单的示例,实际情感分析的实现可能需要更复杂的模型和更多的训练数据。您可以根据自己的需求对代码进行调整和扩展。

0
看了该问题的人还看了