首页 > 其他分享 >百度翻译优化之后

百度翻译优化之后

时间:2023-12-09 23:14:02浏览次数:20  
标签:翻译 String add private json import new 优化 百度

package com.example;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;
import org.json.JSONException;
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 fanyi extends JFrame {

private static final String API_KEY = "dzjU0EZolFp0hpYlKD8ckSpk";
private static final String SECRET_KEY = "XbMab4iuLO4dkkKACNDQw5nONYRjTyv4";

private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

private JTextArea inputTextArea;
private JTextArea outputTextArea;
private JComboBox<String> fromLanguageComboBox;
private JComboBox<String> toLanguageComboBox;


public fanyi() {
// Set up the main frame
setTitle("Translation GUI");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Set up the language options
String[] languages = {"en", "zh"};
fromLanguageComboBox = new JComboBox<>(languages);
toLanguageComboBox = new JComboBox<>(languages);

// Create components
inputTextArea = new JTextArea(10, 40);
inputTextArea.setFont(new Font("SimSun", Font.PLAIN, 16)); // Set font size to 16
outputTextArea = new JTextArea("Translation results will be displayed here.");
outputTextArea.setFont(new Font("SimSun", Font.PLAIN, 16)); // Set font size to 16
outputTextArea.setForeground(new Color(34, 139, 34)); // Set text color to green
outputTextArea.setEditable(false);

JButton translateButton = new JButton("Translate");
translateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
translateText();
}
});

// Set up the layout
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

JPanel inputPanel = new JPanel(new BorderLayout());
inputPanel.add(new JLabel("Input Text:"), BorderLayout.NORTH);
inputPanel.add(new JScrollPane(inputTextArea), BorderLayout.CENTER);

JPanel translationOptionsPanel = new JPanel();
translationOptionsPanel.add(fromLanguageComboBox);
translationOptionsPanel.add(new JLabel("->"));
translationOptionsPanel.add(toLanguageComboBox);

JPanel buttonPanel = new JPanel();
buttonPanel.add(translateButton);

mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(outputTextArea, BorderLayout.CENTER);
mainPanel.add(translationOptionsPanel, BorderLayout.WEST);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);

// Add components to the frame
add(mainPanel);

// Make the frame visible
setVisible(true);
}

private void translateText() {
try {
String inputText = inputTextArea.getText();
String accessToken = getAccessToken();
String translationResult = performTranslation(inputText, accessToken);
System.out.println(inputText);
String translatedText = extractTranslation(translationResult);
outputTextArea.setText(translatedText);
} catch (IOException e) {
e.printStackTrace();
outputTextArea.setText("Error during translation. Check the console for details.");
}
}
private String performTranslation(String text, String accessToken) throws IOException {
String fromLanguage = (String) fromLanguageComboBox.getSelectedItem();
String toLanguage = (String) toLanguageComboBox.getSelectedItem();
MediaType mediaType = MediaType.parse("application/json");
String jsonBody = String.format( "{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"" + text + "\"}", fromLanguage, toLanguage);
RequestBody body = RequestBody.create(mediaType, jsonBody);
Request request = new Request.Builder()
.url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + accessToken)
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.build();
Response response = HTTP_CLIENT.newCall(request).execute();
return response.body().string();

}

private String extractTranslation(String translationResult) {
JsonObject json = JsonParser.parseString(translationResult).getAsJsonObject();
JsonObject resultObject = json.getAsJsonObject("result");
System.out.println(json);
JsonArray translations = resultObject.getAsJsonArray("trans_result");
System.out.println(translations);
JsonObject translation = translations.get(0).getAsJsonObject();
if (json.has("error_code")) {
// 检查是否包含错误码,如果是,处理错误信息
int errorCode = json.get("error_code").getAsInt();
String errorMsg = json.get("error_msg").getAsString();
System.out.println("Translation error: " + errorCode + ", " + errorMsg);
return "Translation not available";
}
if (json.has("trans_result")) {

if (!translations.isJsonNull() && translations.size() > 0) {

if (translation.has("dst")) {
return translation.get("dst").getAsString();
}
}
}
return translation.get("dst").getAsString();
}


private 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();
try {
return new JSONObject(response.body().string()).getString("access_token");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new fanyi();
}
});
}
}

 

标签:翻译,String,add,private,json,import,new,优化,百度
From: https://www.cnblogs.com/mine-my/p/17891978.html

相关文章

  • 1.百度秋招面试题
    1.2024百度提前批Java面试一面1.1算法题:一个长度为n的数组中找出m个最大的数。 思路:将数组排序,然后创建一个长度为m的数组,将原数组下标n-m-1到n-1的数组复制到长度到m的新数组中。publicclassFindMaxM{publicstaticint[]findMaxM(int[]nums,intm){......
  • 通信工程项目中网络优化研究——LW
    选题背景通讯系统工程是一个具有高科技含量的专业知识密集型系统工程,其特点在于信息的快速发展,使得它具有较强的时效性。然而,与其他类型的系统工程不同,通信工程受到许多因素的制约,因此,在进一步优化通信工程时,不宜仅仅依靠成本和进度等策略。一般通信工程中大多数设备都具有不可移......
  • 函数递归求n个数的最大公因数(优化版)
    #include<stdio.h>intret(intx,inty){  inti=1;  if(x%y==0||y%x==0)   return(x>y?y:x);  else  {    while(x%y!=0)    {      i=x%y;      x=y;     ......
  • n个数算最小公倍数(优化版)
    #include<stdio.h>intret(intx,inty){  inti=1;  if(x%y==0||y%x==0)    return(x>y?x:y);  else  {   for(i=1;i<=x*y;i++)    {      i=x*i;      if(i%y==0) ......
  • 深入研究与优化目标检测算法,以提高其性能与适用性的探索性研究
    基于深度学习的目标检测算法分为2类:TwoStage和OneStage。TwoStage:先预设一个区域,改区域称为regionproposal,即一个可能包含待检测物体的预选框(简称RP),再通过卷积神经网络进行样本分类计算。流程是:特征提取->生成RP->分类/回归定位。常见的TwoStage算法有:R-CNN、SPP-Net、Fa......
  • element tree 优化线条树,添加增删改功能
    需求:树状结构,支持操作功能(同级、子级、修改、删除)。根据需求是否展示复选框和操作功能。封装linetree.vue组件:1<template>2<div>3<el-tree:data="list":props=defaultProps:expand-on-click-node="false":default-expand-all="true"4......
  • 前端图片最优化压缩方案
    functioncompressImg(file,quality){varqualitys=0.52if(parseInt((file.size/1024).toFixed(2))<1024){qualitys=0.85}if(5*1024<parseInt......
  • 多开工具对应用程序性能的影响与优化
    多开工具对应用程序性能的影响与优化摘要:随着计算机技术的不断发展,多开工具逐渐成为一种常见的软件应用。然而,使用多开工具可能会对应用程序的性能产生一定的影响。本文将探讨多开工具对应用程序性能的影响,并提供一些优化方法,以改善应用程序在多开环境下的表现。引言:多开工具......
  • 体育产业中的图像识别创新:运动分析与训练优化
     在现代体育产业中,图像识别技术正成为一项重要的创新,为运动员的表现分析、训练优化和比赛策略提供了全新的视角。以下是体育产业中图像识别创新的一些关键应用和优势:1. 运动员动作分析:动作精准度评估: 图像识别技术可用于捕捉运动员的关键动作,分析动作的精准度和流畅度,为提高......
  • 4点搞定Type-C接口的PCB可制造性设计优化!
    Type-C接口逐渐显现出成为未来主流接口的趋势,连一贯坚持用lighting接口的苹果手机也转向使用Type-C接口。Type-C接口具有支持正反插、体积更小、传输速度更快、支持更大的功率传输等优点,因此广泛应用于各种电子设备,包括智能手机,笔记本电脑,平板电脑等。今天我们研究研究如何卓越打......