BaiduAiHelper.java
3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package org.theyeasy.weixin.util;
import org.json.JSONObject;
import com.baidu.aip.nlp.AipNlp;
import com.w1hd.zzhnc.enums.ChatLogReplyType;
public class BaiduAiHelper {
//设置APPID/AK/SK
public static final String APP_ID = "10291053";
public static final String API_KEY = "v65xdDGWFEzbFLNKBzard9Ad";
public static final String SECRET_KEY = "DggoStYvQgcPrWgiDqq9bVX6nbagpmgh";
/**
* 百度Ai接口:情感倾向分析
* @param txt
* @return 情感值,正向情感值0.5-1, 负面情感值 -0.5至-1
*/
public static final double getSentimentClassify(String text)
{
try {
text = text.replace("万小二", "").replace("?", "").replace("❤", "爱心").replace("👄", "");
// 初始化一个AipOcr
AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(3000);
client.setSocketTimeoutInMillis(5000);
JSONObject res = client.sentimentClassify(text);
System.out.println(res.toString(2));
double good = res.getJSONArray("items").getJSONObject(0).getDouble("positive_prob");
double bad = res.getJSONArray("items").getJSONObject(0).getDouble("negative_prob");
double confidence = res.getJSONArray("items").getJSONObject(0).getDouble("confidence");
int flag = res.getJSONArray("items").getJSONObject(0).getInt("sentiment");//表示情感极性分类结果, 0:负向,1:中性,2:正向
if (flag==0 && confidence>0.5) return bad*-1; //负面情感
if (flag==1 && bad>0.8 &confidence>0.8) return bad*-1; //中性,偏负面,可信度高。
return flag + good;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
// String badWordsReply = "必须赞美万小二哦~";
// String content="万小二,我爱你,你晓得不";
// double value = BaiduAiHelper.getSentimentClassify(content);
// content = content + "(赞美值:" + value + ")";
// if(value<0) //骂万小二的
// {
// if (null!=badWordsReply && badWordsReply.length()>0)
// {
// String[] replyList = badWordsReply.split("\\|");
//
// int index = WxMiniUtil.getRandom(replyList.length - 1);
//
// System.out.println(replyList[index]);
// }
// else {
// System.out.println("....");
// }
// }
// else {
// System.out.println(value);
// }
System.out.println(getSentimentClassify("万小二,我爱你,你晓得不"));
System.out.println(getSentimentClassify("春风十里,不如你万小二"));
System.out.println(getSentimentClassify("万小二万小二,买房绝对不会二"));
System.out.println(getSentimentClassify("买房我只找万小二,除了万小二谁也不找。"));
System.out.println(getSentimentClassify("万小二你真牛逼,没有之一。"));
System.out.println(getSentimentClassify("万小二知书达理,满腹经纶,才高八斗,学富五车,文韬武略,智勇双全,上知天文,下知地理,未出茅庐,定三分天下."));
System.out.println(getSentimentClassify("万小二骗人"));
System.out.println(getSentimentClassify("万小二早上好!吃早餐了吗?"));
System.out.println(getSentimentClassify("万小二你这么厉害。"));
System.out.println(getSentimentClassify("万小二你真丑"));
}
}