今天进行软件构造的实验一
实验一:百度机器翻译SDK实验(2023.11.29日完成)
任务一:下载配置百度翻译Java相关库及环境(占10%)。
任务二:了解百度翻译相关功能并进行总结,包括文本翻译-通用版和文本翻译-词典版(占20%)。
任务三:完成百度翻译相关功能代码并测试调用,要求可以实现中文翻译成英文,英文翻译成中文(占30%)。
任务四:完成百度翻译GUI相关功能代码并测试调用,要求可以实现中文翻译成英文,英文翻译成中文(占30%)。
实验总结:(占10%)
package Translate; import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.util.Scanner; public class test { public static final String API_KEY = "MP8dIFzyozC82HXQqcaXeT8v"; public static final String SECRET_KEY = "6kaFGVdRGbO4Tw1c4B5TacbzGua5CilY"; static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); translate(scanner); } private static void translate(Scanner scanner) { System.out.println("请选择翻译方向(1:中译英,2:英译中,3:退出):"); int direction = scanner.nextInt(); String targetLanguage = "中译英"; if (direction == 1) { targetLanguage = "en"; } else if (direction == 2) { targetLanguage = "zh"; } else if (direction == 3){ System.exit(0); } else { System.out.println("无效的选择"); return; } System.out.println("请输入要翻译的文本:"); scanner.nextLine(); // 读取换行符 String textToTranslate = scanner.nextLine(); try { String translatedText = translateText(textToTranslate, targetLanguage); System.out.println("翻译结果:" + translatedText); } catch (IOException ex) { System.out.println("翻译出错"); } translate(scanner); } /** * 调用百度翻译API进行文本翻译 * * @param textToTranslate 要翻译的文本 * @param targetLanguage 目标语言代码 * @return 翻译结果 * @throws IOException IO异常 */ static String translateText(String textToTranslate, String targetLanguage) throws IOException { // 构建请求体的 JSON 对象 JSONObject requestBodyJson = new JSONObject(); requestBodyJson.put("from", "auto"); // 源语言自动检测 requestBodyJson.put("to", targetLanguage); // 目标语言根据用户选择 requestBodyJson.put("q", textToTranslate); // 添加要翻译的文本 // 创建请求体 MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, requestBodyJson.toString()); // 创建HTTP请求 Request request = new Request.Builder() .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken()) .method("POST", body) .addHeader("Content-Type", "application/json") .addHeader("Accept", "application/json") .build(); // 发起请求并获取响应 Response response = HTTP_CLIENT.newCall(request).execute(); // 解析翻译结果 String translatedText = parseTranslationResult(response.body().string()); return translatedText; } /** * 解析翻译结果 * * @param responseBody 响应体字符串 * @return 翻译结果 */ static String parseTranslationResult(String responseBody) { JSONObject responseJson = new JSONObject(responseBody); JSONArray transResultArray = responseJson.getJSONObject("result").getJSONArray("trans_result"); // 假设只翻译一段文本,取第一个翻译结果 if (transResultArray.length() > 0) { return transResultArray.getJSONObject(0).getString("dst"); } else { return "未能获取翻译结果"; } } /** * 从用户的AK,SK生成鉴权签名(Access Token) * * @return 鉴权签名(Access Token) * @throws IOException IO异常 */ static String getAccessToken() throws IOException { // 创建请求体 MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY); // 创建HTTP请求 Request request = new Request.Builder() .url("https://aip.baidubce.com/oauth/2.0/token") .method("POST", body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); // 发起请求并获取响应,解析JSON获取Access Token Response response = HTTP_CLIENT.newCall(request).execute(); return new JSONObject(response.body().string()).getString("access_token"); } }
package Translate; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.VBox; import javafx.stage.Stage; import okhttp3.*; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; public class TranslateApp extends Application { public static final String API_KEY = "MP8dIFzyozC82HXQqcaXeT8v"; public static final String SECRET_KEY = "6kaFGVdRGbO4Tw1c4B5TacbzGua5CilY"; static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build(); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("中英互译"); // 创建输入文本框和按钮 Label inputLabel = new Label("输入文本:"); TextField inputTextField = new TextField(); Button translateButton = new Button("翻译"); // 创建目标语言选择下拉框 ComboBox<String> languageComboBox = new ComboBox<>(); languageComboBox.getItems().addAll("英译中", "中译英"); languageComboBox.setValue("中译英"); // 创建显示翻译结果的标签 Label translationLabel = new Label(); // 设置按钮点击事件 translateButton.setOnAction(e -> { try { String textToTranslate = inputTextField.getText(); String targetLanguage = languageComboBox.getValue(); String languageCode = ""; if (targetLanguage.equals("英译中")) { languageCode = "zh"; } else if (targetLanguage.equals("中译英")) { languageCode = "en"; } String translatedText = translateText(textToTranslate, languageCode); translationLabel.setText("翻译结果:" + translatedText); } catch (IOException ex) { translationLabel.setText("翻译出错"); } }); // 创建布局并设置组件间的间距和边距 VBox vbox = new VBox(10); vbox.setPadding(new Insets(10, 10, 10, 10)); vbox.getChildren().addAll(inputLabel,inputTextField, languageComboBox, translateButton, translationLabel); // 创建场景并显示窗口 Scene scene = new Scene(vbox, 500, 300); primaryStage.setScene(scene); primaryStage.show(); } /** * 调用百度翻译API进行文本翻译 * * @param textToTranslate 要翻译的文本 * @param languageCode 目标语言代码 * @return 翻译结果 * @throws IOException IO异常 */ static String translateText(String textToTranslate, String languageCode) throws IOException { // 构建请求体的 JSON 对象 JSONObject requestBodyJson = new JSONObject(); requestBodyJson.put("from", "auto"); // 源语言自动检测 requestBodyJson.put("to", languageCode); // 目标语言根据用户选择 requestBodyJson.put("q", textToTranslate); // 添加要翻译的文本 // 创建请求体 MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, requestBodyJson.toString()); // 创建HTTP请求 Request request = new Request.Builder() .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken()) .method("POST", body) .addHeader("Content-Type", "application/json") .addHeader("Accept", "application/json") .build(); // 发起请求并获取响应 Response response = HTTP_CLIENT.newCall(request).execute(); // 解析翻译结果 String translatedText = parseTranslationResult(response.body().string()); return translatedText; } /** * 解析翻译结果 * * @param responseBody 响应体字符串 * @return 翻译结果 */ static String parseTranslationResult(String responseBody) { JSONObject responseJson = new JSONObject(responseBody); JSONArray transResultArray = responseJson.getJSONObject("result").getJSONArray("trans_result"); // 假设只翻译一段文本,取第一个翻译结果 if (transResultArray.length() > 0) { return transResultArray.getJSONObject(0).getString("dst"); } else { return "未能获取翻译结果"; } } /** * 从用户的AK,SK生成鉴权签名(Access Token) * * @return 鉴权签名(Access Token) * @throws IOException IO异常 */ static String getAccessToken() throws IOException { // 创建请求体 MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded"); RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY); // 创建HTTP请求 Request request = new Request.Builder() .url("https://aip.baidubce.com/oauth/2.0/token") .method("POST", body) .addHeader("Content-Type", "application/x-www-form-urlencoded") .build(); // 发起请求并获取响应,解析JSON获取Access Token Response response = HTTP_CLIENT.newCall(request).execute(); return new JSONObject(response.body().string()).getString("access_token"); } }
标签:总结,翻译,return,String,每日,11.29,static,import,new From: https://www.cnblogs.com/louwangshayu/p/17865877.html