本文目录导读:

我来介绍几种Java实现情感分析的方法:
使用第三方API(推荐)
百度AI情感分析
import com.baidu.aip.nlp.AipNlp;
public class BaiduSentimentAnalysis {
private static final String APP_ID = "你的AppId";
private static final String API_KEY = "你的ApiKey";
private static final String SECRET_KEY = "你的SecretKey";
public static void main(String[] args) {
AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
String text = "这家餐厅的菜品非常美味,环境也很优雅!";
// 调用情感分析
org.json.JSONObject result = client.sentimentClassify(text);
System.out.println(result.toString(2));
}
}
使用Stanford CoreNLP
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import java.util.Properties;
public class StanfordSentimentAnalysis {
public static void main(String[] args) {
// 初始化管道
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
String text = "This movie is amazing! I love it.";
// 创建文档对象
CoreDocument document = new CoreDocument(text);
pipeline.annotate(document);
// 分析情感
for (CoreSentence sentence : document.sentences()) {
String sentiment = sentence.sentiment();
System.out.println("句子: " + sentence.text());
System.out.println("情感: " + sentiment);
}
}
}
简单规则引擎实现
import java.util.*;
public class SimpleSentimentAnalyzer {
private static final Set<String> POSITIVE_WORDS = new HashSet<>(Arrays.asList(
"好", "棒", "优秀", "喜欢", "满意", "推荐", "美味", "开心", "漂亮", "实惠"
));
private static final Set<String> NEGATIVE_WORDS = new HashSet<>(Arrays.asList(
"差", "烂", "糟糕", "讨厌", "失望", "不推荐", "难吃", "伤心", "难看", "贵"
));
private static final Set<String> INTENSIFIERS = new HashSet<>(Arrays.asList(
"非常", "很", "太", "极其", "特别", "超级"
));
public static String analyze(String text) {
int score = 0;
int intensity = 1;
String[] words = text.split("[,。!?\\s]+");
for (String word : words) {
if (INTENSIFIERS.contains(word)) {
intensity = 2;
continue;
}
if (POSITIVE_WORDS.contains(word)) {
score += intensity;
} else if (NEGATIVE_WORDS.contains(word)) {
score -= intensity;
}
intensity = 1; // 重置强度
}
if (score > 0) {
return "正面 (得分: " + score + ")";
} else if (score < 0) {
return "负面 (得分: " + score + ")";
} else {
return "中性 (得分: 0)";
}
}
public static void main(String[] args) {
System.out.println(analyze("这家餐厅非常好,菜品特别美味!"));
System.out.println(analyze("服务很糟糕,太失望了。"));
System.out.println(analyze("今天天气不错。"));
}
}
使用DL4J深度学习
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.util.ModelSerializer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
public class DeepLearningSentiment {
private MultiLayerNetwork model;
public DeepLearningSentiment() throws Exception {
// 加载预训练模型
model = ModelSerializer.restoreMultiLayerNetwork("model.zip");
}
public String predict(String text) {
// 文本预处理和向量化
INDArray features = preprocessText(text);
// 预测
INDArray output = model.output(features);
// 解析结果
double positive = output.getDouble(0, 0);
double negative = output.getDouble(0, 1);
return positive > negative ? "正面" : "负面";
}
private INDArray preprocessText(String text) {
// 实现文本到向量的转换
// 这里简化处理
return Nd4j.create(new double[]{1, 300});
}
}
Maven依赖配置
<!-- Stanford CoreNLP -->
<dependency>
<groupId>edu.stanford.nlp</groupId>
<artifactId>stanford-corenlp</artifactId>
<version>4.5.0</version>
</dependency>
<!-- 百度AI SDK -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.2</version>
</dependency>
<!-- DL4J -->
<dependency>
<groupId>org.deeplearning4j</groupId>
<artifactId>deeplearning4j-core</artifactId>
<version>1.0.0-M2.1</version>
</dependency>
推荐方案
对于大多数Java项目,建议:
- 商业项目:使用百度/阿里云等第三方API
- 学习研究:使用Stanford CoreNLP
- 简单场景:自己实现规则引擎
- 高性能需求:使用DL4J等深度学习框架
选择哪种方案取决于你的具体需求、预算和技术栈。