溫馨提示×

如何用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());

        // 創(chuàng)建分類器
        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);
        }
    }
}

在上面的示例中,我們首先從文本文件中讀取訓練數(shù)據(jù),然后使用 DocumentCategorizerME.train 方法訓練模型。接著創(chuàng)建一個 DocumentCategorizerME 分類器,并用它來對文本進行情感分析。在這個示例中,我們使用了一個包含三句話的測試集來測試分類器的性能。

請注意,這只是一個簡單的示例,實際情感分析的實現(xiàn)可能需要更復雜的模型和更多的訓練數(shù)據(jù)。您可以根據(jù)自己的需求對代碼進行調整和擴展。

0