首页 > 其他分享 >2023-12-02学习总结

2023-12-02学习总结

时间:2023-12-03 10:46:40浏览次数:43  
标签:02 12 String import valuesLanguage 2023 put new GBC

百度机器翻译SDK实验

package com.step04;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;

public class TranslationGUI {
    private JFrame transFrame;
    private JButton transButton;
    private JTextArea sendText;
    private JTextArea receiveText;
    private JComboBox boxSendLanguage;
    private String sendType="自动检测";
    private JComboBox boxReciveLanguage;
    private String receiveType="汉语";

    private String[] listSendLanguage ={"自动检测","汉语","英语","俄语","日语",
            "韩语","法语","西班牙语","德语"
            ,"意大利语","葡萄牙语","越南语","印尼语"
            ,"马来语","泰语","阿拉伯语","印地语"
            ,"土耳其语","希腊语","匈牙利语"};
    private String[] listReceiveLanguage ={"汉语","英语","俄语","日语",
            "韩语","法语","西班牙语","德语"
            ,"意大利语","葡萄牙语","越南语","印尼语"
            ,"马来语","泰语","阿拉伯语","印地语"
            ,"土耳其语","希腊语","匈牙利语"};
    private JSONObject valuesLanguage = new JSONObject();
    public TranslationGUI() throws JSONException {
        Translatator translatator = new Translatator();
        valuesLanguage.put("自动检测", "auto");
        valuesLanguage.put("汉语", "zh");
        valuesLanguage.put("英语", "en");
        valuesLanguage.put("俄语", "ru");
        valuesLanguage.put("日语", "jp");
        valuesLanguage.put("韩语", "kor");
        valuesLanguage.put("法语", "fra");
        valuesLanguage.put("西班牙语", "spa");
        valuesLanguage.put("德语", "de");
        valuesLanguage.put("意大利语", "it");
        valuesLanguage.put("葡萄牙语", "pt");
        valuesLanguage.put("越南语", "vie");
        valuesLanguage.put("印尼语", "id");
        valuesLanguage.put("马来语", "may");
        valuesLanguage.put("泰语", "th");
        valuesLanguage.put("阿拉伯语", "ara");
        valuesLanguage.put("印地语", "hi");
        valuesLanguage.put("土耳其语", "tr");
        valuesLanguage.put("希腊语", "el");
        valuesLanguage.put("匈牙利语", "hu");

        transFrame = new JFrame("百度翻译mini版");
        transFrame.setSize(800, 400);
        transFrame.setLocationRelativeTo(null);
        transFrame.setResizable(false);//不可缩放
        /**
         * 设置窗口关闭按钮点击后的默认操作, 参考值:
         *     WindowConstants.DO_NOTHING_ON_CLOSE: 不执行任何操作。
         *     WindowConstants.HIDE_ON_CLOSE: 隐藏窗口(不会结束进程), 再次调用 setVisible(true) 将再次显示。
         *     WindowConstants.DISPOSE_ON_CLOSE: 销毁窗口, 如果所有可显示的窗口都被 DISPOSE, 则可能会自动结束进程。
         *     WindowConstants.EXIT_ON_CLOSE: 退出进程。
         */
        transFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel bodyPanel = new JPanel();
        bodyPanel.setSize(new Dimension(600, 300));

        JPanel sendPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        sendPanel.setBackground(Color.GRAY);
        sendText = new JTextArea(11,17);
        sendText.setFont(new Font("微软雅黑", Font.PLAIN, 20));
        sendText.setBackground(Color.WHITE);

        sendPanel.add(sendText);

        JPanel transPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        transPanel.setPreferredSize(new Dimension(100, 100));
        transButton = new JButton("翻译->");
        transButton.setSize(100,20);
        transButton.addActionListener(e -> {
            String request = sendText.getText();
            if(sendType == receiveType){
                JOptionPane.showMessageDialog(null, "无法把"+sendType+"翻译成"+receiveType);
            }else if(request.length() > 0){
                String temp = sendText.getText();
                try {
                    receiveText.setText(translatator.getReceiveText(temp,valuesLanguage.getString(sendType),valuesLanguage.getString(receiveType)));
                } catch (JSONException ex) {
                    JOptionPane.showMessageDialog(null, "翻译出现异常");
                }
            }else{
                JOptionPane.showMessageDialog(null, "请输入要翻译的内容");
            }
        });

        boxSendLanguage = new JComboBox<>(listSendLanguage);
        boxSendLanguage.setSize(30,20);
        boxSendLanguage.addItemListener(e -> {
            if(e.getStateChange() == ItemEvent.SELECTED){
                sendType = (String) e.getItem();
                System.out.println("s:"+sendType);
            }
        });
        boxReciveLanguage = new JComboBox<>(listReceiveLanguage);
        boxReciveLanguage.addItemListener(e -> {
            if(e.getStateChange() == ItemEvent.SELECTED){
                receiveType = (String) e.getItem();
                System.out.println("r:"+receiveType);
            }
        });
        transPanel.add(boxSendLanguage);
        transPanel.add(transButton);
        transPanel.add(boxReciveLanguage);

        JPanel receivePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        receivePanel.setBackground(Color.GRAY);
        receiveText = new JTextArea(11,17);
        receiveText.setBackground(Color.WHITE);
        receiveText.setFont(new Font("微软雅黑", Font.PLAIN, 20));

        receiveText.setEditable(false);
        receivePanel.add(receiveText);

        GridBagConstraints GBC = new GridBagConstraints();
        GBC.gridx = 0;
        GBC.gridy = 0;
        GBC.gridwidth = 4;
        GBC.gridheight = 1;
        bodyPanel.add(sendPanel, GBC);

        GBC.gridx = 0;
        GBC.gridy = 0;
        GBC.gridwidth = 1;
        GBC.gridheight = 1;
        bodyPanel.add(transPanel, GBC);

        GBC.gridx = 0;
        GBC.gridy = 0;
        GBC.gridwidth = 4;
        GBC.gridheight = 1;
        bodyPanel.add(receivePanel, GBC);

        transFrame.setContentPane(bodyPanel);
        transFrame.setVisible(true);
    }
    public static void main(String[] args) throws JSONException {
        new TranslationGUI();
    }
}
package com.step04;

import com.google.gson.JsonArray;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Translatator {
    private String CLIENT_ID = "jnR7w5p8sNrvnatsXE5NrNLX";
    private String API_KEY = "jnR7w5p8sNrvnatsXE5NrNLX";
    private String SECRET_KEY = "aloZ33pgdYR1qnjmOhHvvX54j3C6Rchl";

    public String getAccessToken() {
        try{
            URL url = new URL("https://aip.baidubce.com/oauth/2.0/token?client_id="+API_KEY+"&client_secret="+SECRET_KEY+"&grant_type=client_credentials");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                System.out.println("responseCode:"+responseCode);
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("response:"+response.toString());
                JSONObject jsonObject = new JSONObject(response.toString());
                return jsonObject.getString("access_token");
            }else {
                System.out.println("responseCode:" + responseCode);
            }
            httpURLConnection.disconnect();
        }catch (IOException e){
            e.printStackTrace();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    public String getResult(String sendText,String sendLanguage,String receiveLanguage) {
        try{
            URL url = new URL("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token="+getAccessToken());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            String requestBody = "{\"from\":\""+sendLanguage+"\"," +
                    "\"to\":" + "\"" + receiveLanguage + "\","+
                    "\"q\":"+ "\"" + sendText + "\"}";
            //设置请求体
            System.out.println(requestBody);
            httpURLConnection.setDoOutput(true);
            try(OutputStream outputStream = httpURLConnection.getOutputStream()){
                byte[] input = requestBody.getBytes("UTF-8");
                outputStream.write(input, 0, input.length);
            }
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                // 输出响应数据
                return response.toString();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }
    public String  getReceiveText(String sendText,String sendLanguage,String receiveLanguage) {
        try{
            Translatator translatator = new Translatator();
            JSONObject jsonObject1 = new JSONObject(translatator.getResult(sendText,sendLanguage,receiveLanguage));
            JSONObject jsonObject2 = new JSONObject(jsonObject1.getString("result"));
            System.out.println(jsonObject2.toString());
            JSONArray jsonArray = jsonObject2.getJSONArray("trans_result");
            String dst = jsonArray.getJSONObject(0).getString("dst");
            System.out.println(dst);
            return dst;
        }catch (JSONException e){
            e.printStackTrace();
        }
        return "";
    }
}

本次实验难点在于理解java发起http请求并获取网页返回的数据

标签:02,12,String,import,valuesLanguage,2023,put,new,GBC
From: https://www.cnblogs.com/xxaxf/p/17872665.html

相关文章

  • 2023-2024-1 20231317 《计算机基础与程序设计》第十周学习总结
    作业信息这个作业属于哪个课程<班级的链接>(如2023-2024-1-计算机基础与程序设计)这个作业要求在哪里<作业要求的链接>(如2023-2024-1计算机基础与程序设计第十周作业)这个作业的目标<《C语言程序设计第9章》《计算机科学概论第12、13、14章》>作业正文https://w......
  • 2302. 统计得分小于 K 的子数组数目(双指针,贡献法,子数组问题)
     枚举子数组问题,常见有固定一个点,枚举另一个端点,还有枚举中间点。本题使用双指针算法,对右端点进行枚举,每次累加[l,r]区间内,所有以右端点为结尾的子数组对答案的贡献度,也就是长度r-l+1classSolution:defcountSubarrays(self,nums:List[int],k:int)->int:......
  • # 2023-2024-1 20231308 《计算机基础与程序设计》第十周学习总结
    2023-2024-120231308《计算机基础与程序设计》第十周学习总结作业信息这个作业属于哪个课程2023-2024-1-计算机基础与程序设计这个作业要求在哪里2023-2024-1计算机基础与程序设计第十周作业这个作业的目标信息系统、数据库与SQL、人工智能与专家系统、人工神经......
  • 工作感受月记(202312月)
    2023年12月01号周五遇月初。最近工作事项多,被案例和杂事所困扰。今日工作事项:1/policy的案例,一个是写policy,一个是调查policy的执行过程,为什么一个删除的资源还在被policyscan呢?2/一个案例appservice的性能不稳定,为什么会偶发性出现响应在10秒以上的情况呢?这个问题还需......
  • CTT2023 邮寄
    从广州被邮寄到了苏州。还有点感冒有点咳嗽,体温37度。还是来了。Day0清早坐xp的车,早上坐飞机,中午坐高铁,下午坐大巴,风尘仆仆地赶到了苏州。飞机上有一套省选题要验,看了两眼,T1奇怪式子题,没笔没法推;T2神秘拉插,胡了个不知道对不对的东西;T3神秘斜率/拉格朗日橙子,还没会细节......
  • 2023-2024-1 20231304 《计算机基础与程序设计》第十周学习总结
    2023-2024-120231304《计算机基础与程序设计》第十周学习总结作业信息这个作业属于哪个课程2023-2024-1-计算机基础与程序设计这个作业要求在哪里2023-2024-1计算机基础与程序设计第十周作业这个作业的目标信息系统、数据库与SQL、人工智能与专家系统、人工神经......
  • CF1288题解
    CF1288EducationalCodeforcesRound80(RatedforDiv.2)A略CF1288BlinkCF1288B题意给定\(A,B\),问有多少个二元组\((a,b)\)满足\(1\lea\leA,1\leb\leB\)且\(a\cdotb+a+b=\operatorname{conc}(a,b)\)。其中\(\operatorname{conc}(a,b)\)表示将\(a,b\)......
  • 2023-2024-1 20231307《计算机基础与程序设计》第十周学习总结
    作业信息这个作业属于哪个课程2023-2024-1-计算机基础与程序设计这个作业要求在哪里2023-2024-1计算机基础与程序设计第10周作业这个作业的目标自学计算机科学概论第12,13,14章 作业正文https://www.cnblogs.com/lzt-/p/17872592.html教材学习内容总结第十......
  • 2023-2024-1 20231405《计算机基础与程序设计》第十周学习总结
    2023-2024-120231405《计算机基础与程序设计》第十周学习总结作业信息作业属于哪个课程https://edu.cnblogs.com/campus/besti/2023-2024-1-CFAP作业要求在哪里https://edu.cnblogs.com/campus/besti/2023-2024-1-CFAP/homework/13009作业的目标自学《计......
  • 12.2日记
    Scala是一门以Java虚拟机(JVM)为运行环境并将面向对象和函数式编程的最佳特性结合在一起的静态类型编程语言(静态语言需要提前编译的如:Java、C、C++等,动态语言如:JS)。1)Scala是一门多范式的编程语言,Scala支持面向对象和函数式编程。(多范式,就是多种编程方法的意思。有面向过程、面......