2024.11.23

任务二:了解百度翻译相关功能并进行总结,包括文本翻译-通用版和文本翻译-词典版

百度翻译利用丰富的互联网数据和先进的机器翻译技术,推出了全球首个互联网神经网络翻译系统。该系统支持200多种语言之间的互译,涵盖了超过4万个语言方向,每天处理千亿字符的翻译请求,旨在帮助用户克服语言障碍。

通用版文本翻译是百度翻译基于其领先的自然语言处理技术推出的在线翻译服务,支持包括中文、英文、日文和韩文在内的200多种语言互译,并能够自动检测100多种语言。

词典版在通用版的基础上,增加了词典资源和语音合成功能。词典资源主要包括中英词典,由于不同词汇的属性各异,词典结果可能不涵盖所有内容。例如,当源语言为中文时,词典数据将包括拼音、词性、中文和英文释义、近义词等信息;而当源语言为英文时,词典数据则包含英文释义、中文释义、音标和核心词汇类别等内容。

任务三:完成百度翻译相关功能代码并测试调用,要求可以实现中文翻译成英文,英文翻译成中文

在主函数写一个选择翻译的方法,1为中文翻译英文 2为英文翻译中文

 

package org.example.baidu;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class TranslationGUI {
private static final String API_KEY = "nC0pwjaVG2dsWYdTYZQkZPxT";
private static final String SECRET_KEY = "ZAQuKUBfqXIL8gjlqLRkdQ3FC7VNW7qe";
private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

private JFrame frame;
private JTextField textFieldInput;
private JButton buttonTranslate;
private JLabel labelResult;
private JComboBox<String> comboBoxLanguage;

public TranslationGUI() {
initialize();
}

private void initialize() {
frame = new JFrame("Simple Translator");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);

JLabel labelChoose = new JLabel("请选择翻译方式:");
labelChoose.setBounds(10, 11, 85, 14);
frame.getContentPane().add(labelChoose);

comboBoxLanguage = new JComboBox<>(new String[] {"中文翻译成英文", "英文翻译成中文"});
comboBoxLanguage.setBounds(100, 8, 200, 20);
frame.getContentPane().add(comboBoxLanguage);

textFieldInput = new JTextField();
textFieldInput.setBounds(10, 50, 414, 20);
frame.getContentPane().add(textFieldInput);
textFieldInput.setColumns(10);

buttonTranslate = new JButton("翻译");
buttonTranslate.setBounds(10, 100, 89, 23);
frame.getContentPane().add(buttonTranslate);

labelResult = new JLabel("");
labelResult.setBounds(10, 150, 414, 14);
frame.getContentPane().add(labelResult);

buttonTranslate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String textToTranslate = textFieldInput.getText();
String from = "zh";
String to = "en";
if (comboBoxLanguage.getSelectedIndex() == 1) {
from = "en";
to = "zh";
}
String translatedText = translateText(textToTranslate, from, to);
labelResult.setText("翻译结果: " + translatedText);
} catch (IOException ex) {
ex.printStackTrace();
labelResult.setText("翻译失败: " + ex.getMessage());
}
}
});
}

public static String translateText(String text, String from, String to) throws IOException {
MediaType mediaType = MediaType.parse("application/json");
JSONObject jsonBody = new JSONObject();
jsonBody.put("from", from); // 源语言
jsonBody.put("to", to); // 目标语言
jsonBody.put("q", text); // 等待翻译的文本

RequestBody body = RequestBody.create(mediaType, jsonBody.toString());
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 responseBody = response.body().string();

JSONObject jsonResponse = new JSONObject(responseBody);

// 检查是否存在错误
if (jsonResponse.has("error_code")) {
int errorCode = jsonResponse.getInt("error_code");
String errorMsg = jsonResponse.getString("error_msg");
throw new IOException("API Error: " + errorCode + " - " + errorMsg);
}

// 从 result 中提取 trans_result
JSONArray transResultArray = jsonResponse.getJSONObject("result").getJSONArray("trans_result");
return transResultArray.getJSONObject(0).getString("dst"); // 获取翻译结果
}

public 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);
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();
Response response = HTTP_CLIENT.newCall(request).execute();
return new JSONObject(response.body().string()).getString("access_token");
}

public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
TranslationGUI window = new TranslationGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}

 

posted @ 2024-11-23 09:19  kuku睡  阅读(10)  评论(0)    收藏  举报