How to use Java to connect Baidu AI interface for sentiment analysis
Introduction:
In modern society, sentiment analysis has become an important application field of artificial intelligence. Through sentiment analysis, we can understand users' emotional attitudes towards specific things or topics, which is of great significance to fields such as market research, social media monitoring, and emotional response. Baidu AI platform provides a sentiment analysis API. Using this API, we can perform sentiment analysis on text and quickly and accurately determine the emotional tendency of the text. This article will introduce how to use Java to connect Baidu AI interface for sentiment analysis, and give corresponding code examples.
1. Register for Baidu AI platform and obtain API Key and Secret Key
To use the sentiment analysis API of Baidu AI platform, you first need to register a Baidu AI developer account and create an application. Enter the Baidu AI Developer Platform (https://ai.baidu.com) and log in, and follow the prompts to register your account and conduct real-name authentication. After completing the registration, create a new application, select the "Sentiment Analysis" service, and obtain the API Key and Secret Key.
2. Import Java SDK
Baidu AI platform provides a Java version of SDK, which can easily use the sentiment analysis API in Java projects. First, you need to download the Java SDK. You can find the Java SDK on the "SDK Download" page of the Baidu AI Developer Platform and unzip the downloaded file. Import the unzipped folder into the Java project.
3. Introduce dependencies
Add the following dependencies in the pom.xml of the Java project:
<dependencies> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20190722</version> </dependency> </dependencies>
4. Write code to implement sentiment analysis
The sample code is as follows:
import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class SentimentAnalysis { public static void main(String[] args) { String apiKey = "YOUR_API_KEY"; String secretKey = "YOUR_SECRET_KEY"; String text = "今天天气真好"; try { String result = sentimentAnalysis(apiKey, secretKey, text); JSONObject jsonObject = new JSONObject(result); int sentiment = jsonObject.getJSONObject("items").getInt("sentiment"); System.out.println("情感倾向: " + sentiment); } catch (Exception e) { e.printStackTrace(); } } public static String sentimentAnalysis(String apiKey, String secretKey, String text) throws Exception { String url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify"; String param = "text=" + URLEncoder.encode(text, "UTF-8"); String accessToken = getAccessToken(apiKey, secretKey); url = url + "?charset=UTF-8&access_token=" + accessToken; URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length)); connection.setDoOutput(true); connection.getOutputStream().write(param.getBytes()); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } public static String getAccessToken(String apiKey, String secretKey) throws Exception { String grantType = "client_credentials"; String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=" + grantType + "&client_id=" + apiKey + "&client_secret=" + secretKey; URL realUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = in.readLine()) != null) { result.append(line); } JSONObject jsonObject = new JSONObject(result.toString()); String accessToken = jsonObject.getString("access_token"); return accessToken; } }
Please replace YOUR_API_KEY
and YOUR_SECRET_KEY
in the code with your own API Key and Secret Key.
Through the above code, we first call the sentimentAnalysis
method to perform sentiment analysis, and convert the analysis results into JSON objects to extract emotional tendencies. Finally, print out the emotional tendencies.
Conclusion:
This article introduces how to use Java to connect Baidu AI interface for sentiment analysis. Through the sentiment analysis API provided by Baidu AI platform, we can quickly and easily perform sentiment analysis on text, which can be applied in multiple fields and scenarios. I hope this article can help readers quickly get started with the sentiment analysis API and understand how to implement sentiment analysis functions in Java projects.
The above is the detailed content of How to use Java to connect Baidu AI interface for sentiment analysis. For more information, please follow other related articles on the PHP Chinese website!