12月25日打卡

发布时间 2023-12-25 17:41:38作者: 周+⑦

今天完成优化了一下软件构造的实验一的相关内容。

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

Sample.java

import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

class Sample {
    public static final String API_KEY = "8hVSvhLnLzYSeROG6aTXdGrb";
    public static final String SECRET_KEY = "T9iIWYQ7tKDv7jWGTZBgUQjyRVfzsG42";

    public static void main(String[] args) throws IOException {
        // 示例用法:
        System.out.println("翻译 'hello' 英译汉: " + translate("hello", "en", "zh"));
        System.out.println("翻译 '你好' 汉译英: " + translate("你好", "zh", "en"));
    }

    static String translate(String text, String from, String to) throws IOException {
        String accessToken = getAccessToken();
        String encodedText = URLEncoder.encode(text, "UTF-8");
        String urlStr = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + accessToken;
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        String jsonContent = new JSONObject()
                .put("q", text)
                .put("from", from)
                .put("to", to)
                .toString();

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = jsonContent.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            String responseStr = response.toString();
            System.out.println("Response from API: " + responseStr); // 打印响应内容

            JSONObject responseObject = new JSONObject(responseStr);
            JSONObject resultObject = responseObject.getJSONObject("result"); // 获取 "result" 对象
            return resultObject.getJSONArray("trans_result").getJSONObject(0).getString("dst");
        } catch (JSONException e) {
            e.printStackTrace();
            return "分析JSON响应时出错: " + e.getMessage();
        }
    }

    static String getAccessToken() throws IOException {
        String authHost = "https://aip.baidubce.com/oauth/2.0/token";
        URL url = new URL(authHost);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);

        String params = "grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;

        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = params.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            JSONObject responseObject = new JSONObject(response.toString());
            return responseObject.getString("access_token");
        }
    }
}

SampleGUI.java

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

public class SampleGUI {
    private JFrame frame;
    private JTextField textFieldInput;
    private JTextArea textAreaOutput;
    private JComboBox<String> comboBoxLanguage;
    private JButton btnTranslate;
    private JLabel labelInput;
    private JLabel labelOutput;
    private JLabel labelLanguage;

    public SampleGUI() {
        initialize();
    }

    private void initialize() {
        // 创建主框架
        frame = new JFrame("翻译工具");
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridBagLayout());

        // 初始化组件
        labelInput = new JLabel("请输入:");
        labelOutput = new JLabel("翻译内容:");
        labelLanguage = new JLabel("请选择:");

        textFieldInput = new JTextField(20);
        textAreaOutput = new JTextArea(5, 20);
        textAreaOutput.setEditable(false);

        comboBoxLanguage = new JComboBox<>(new String[]{"英译汉", "汉译英"});
        btnTranslate = new JButton("翻译");

        // 设置布局并添加组件
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.insets = new Insets(10, 10, 10, 10);

        constraints.gridx = 0;
        constraints.gridy = 0;
        frame.add(labelInput, constraints);

        constraints.gridx = 1;
        frame.add(textFieldInput, constraints);

        constraints.gridx = 0;
        constraints.gridy = 1;
        frame.add(labelLanguage, constraints);

        constraints.gridx = 1;
        frame.add(comboBoxLanguage, constraints);

        constraints.gridx = 0;
        constraints.gridy = 2;
        frame.add(labelOutput, constraints);

        constraints.gridy = 3;
        constraints.gridx = 0;
        constraints.gridwidth = 2;
        frame.add(new JScrollPane(textAreaOutput), constraints);

        constraints.gridy = 4;
        constraints.fill = GridBagConstraints.NONE;
        frame.add(btnTranslate, constraints);

        // 添加翻译功能按钮
        btnTranslate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String inputText = textFieldInput.getText();
                String selectedLanguage = (String) comboBoxLanguage.getSelectedItem();
                String fromLang, toLang;

                // 根据组合框中的所选项目确定翻译方向
                if ("英译汉".equals(selectedLanguage)) {
                    fromLang = "en";
                    toLang = "zh";
                } else if ("汉译英".equals(selectedLanguage)) {
                    fromLang = "zh";
                    toLang = "en";
                } else {
                    // 只是为了防止意外值,默认为英文到中文
                    fromLang = "en";
                    toLang = "zh";
                }

                try {
                    String translatedText = Sample.translate(inputText, fromLang, toLang);
                    textAreaOutput.setText(translatedText);
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                    textAreaOutput.setText("错误: 不能翻译该文本。");
                }
            }
        });

        // 显示框架
        frame.setVisible(true);
    }

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

运行结果:

 需要的jar包:

 

参考资料:https://ai.baidu.com/ai-doc/index/MT

    https://cloud.baidu.com/doc/MT/index.html

https://console.bce.baidu.com/tools/?_=1669807341890#/api?product=AI&project=%E6%9C%BA%E5%99%A8%E7%BF%BB%E8%AF%91&parent=%E9%89%B4%E6%9D%83%E8%AE%A4%E8%AF%81%E6%9C%BA%E5%88%B6&api=oauth%2F2.0%2Ftoken&method=post