Java调用百度翻译API和调用有道翻译API进行翻译

您所在的位置:网站首页 文件英文翻译成中文怎么写的 Java调用百度翻译API和调用有道翻译API进行翻译

Java调用百度翻译API和调用有道翻译API进行翻译

2024-07-04 16:07| 来源: 网络整理| 查看: 265

目录

界面编写

调用百度API

调用有道API

源代码

界面编写

我们首先需要设计出这个翻译程序的GUI界面,我们写一个类继承自JFrame类,用来展示程序的主窗口,设置好窗口的名称和大小,设置在关闭窗口时终止程序,为了界面的美观,我们将布局设置为流式布局,居中对齐。

接下来准备使用四个panel作为容器让整个界面分为四行。

首先第一行显示中文原文的label和输入框,以及一个翻译按钮。

第二行显示百度翻译label和一行用于显示百度翻译后的译文的文本显示框。

类似的,第三行显示有道翻译label和文本显示框。

最后一行显示相同部分的label和文本显示框。

最后在主函数上,在Swing事件调度线程上执行窗口的显示,这里为了方便,使用了一个lambda匿名函数。

运行程序看看显示的效果,可见美观性还是具有的,因为其实我们是经过多次测试确定下来窗口的大小和组件的长度,使得整个页面看起来比较整齐。

调用百度API

接下来我们需要调用翻译API实现功能。

首先使用百度账号登录百度翻译开发平台,百度翻译开放平台 (baidu.com),注册成为开发者。

然后在百度翻译开放平台 (baidu.com)开通通用翻译API服务。

选择开通标准版就行。

稍微写一下申请表格。

然后在管理控制台就可以看到调用API所需要的APP ID和密钥。

根据官方文档通用翻译API接入文档的教程,我们需要拼接出请求参数加密,这里可以借助百度写好的DEMO,下载Java版本的demo。

解压后将包com放到我们的项目源码目录下。

然后在项目中导入这个包。

然后通过传入APP ID和密钥调用API将中文翻译成英文。

我们给点击按钮添加一个监听事件,当按钮被点击时执行这个lambda匿名函数,在函数中将百度翻译的文本显示在文本框上。

运行程序测试一下百度翻译,这个返回的结果貌似不是我们想要的理想结果。

通过查阅官方文档知道返回的结果是一个JSON对象。

Java中并没有内置JSON的解析,如果要处理JSON必须要借助第三方库,我们这里可以简单的使用正则表达式来提取翻译结果。

再次运行程序,这个可以输出我们想要的翻译结果了。

调用有道API

同理,需要调用有道翻译API,我们需要进行类似的流程操作。

在有道智云 (youdao.com)注册成为开发者。

然后创建应用。

创建完应用后就可以查看到应用ID和应用密钥了。

同样下载有道写好的Java版本demo下来。

我们把有道的软件包放到项目中,和百度的软件包放在一起。

然后把pom.xml也放到项目目录下,点击加载maven项目,将软件包里面的TranslateDemo.java拉出来放到项目源代码目录下,重命名为YouDaoAPI.java,我们将修改这个程序。

首先添加YouDaoAPI的构造函数,为应用ID和应用密钥赋值。

然后将创建请求参数的函数修改为通过传入参数设置请求参数。

最后把主函数修改为对外的翻译接口,通过传入的原文和原语言与目标翻译语言调用创建请求参数函数,返回请求相应。

然后通过传入APP ID和密钥调用API将中文翻译成英文。

同样的,我们通过正则表达式来提取翻译结果。

运行程序,可见翻译成功。

源代码

TranslationDemo.java

import javax.swing.*; import java.awt.*; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.baidu.translate.demo.TransApi; public class TranslationDemo extends JFrame { private JLabel inputLabel, baiduLabel, youdaoLabel, commonLabel; private JTextField inputText, baiduTranslation, youdaoTranslation, commonTextArea; private JButton translateButton; public TranslationDemo() { setTitle("中译英 Demo"); setSize(500, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(1)); inputLabel = new JLabel("中文原文:"); inputText = new JTextField(33); translateButton = new JButton("翻译"); JPanel panel1 = new JPanel(); panel1.add(inputLabel); panel1.add(inputText); panel1.add(translateButton); add(panel1); baiduLabel = new JLabel("百度翻译:"); baiduTranslation = new JTextField(40); baiduTranslation.setEditable(false); JPanel panel2 = new JPanel(); panel2.add(baiduLabel); panel2.add(baiduTranslation); add(panel2); youdaoLabel = new JLabel("有道翻译:"); youdaoTranslation = new JTextField(40); youdaoTranslation.setEditable(false); JPanel panel3 = new JPanel(); panel3.add(youdaoLabel); panel3.add(youdaoTranslation); add(panel3); commonLabel = new JLabel("相同部分:"); commonTextArea = new JTextField(40); commonTextArea.setEditable(false); JPanel panel4 = new JPanel(); panel4.add(commonLabel); panel4.add(commonTextArea); add(panel4); translateButton.addActionListener(e -> { String inputText = this.inputText.getText(); String outputBaidu, outputYouDao, same; try { outputBaidu = translateUsingBaidu(inputText); outputYouDao = translateUsingYoudao(inputText); } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } Pattern pattern = Pattern.compile("\"dst\":\"(.*?)\""); Matcher matcher = pattern.matcher(outputBaidu); if (matcher.find()) outputBaidu = matcher.group(1); baiduTranslation.setText(outputBaidu); pattern = Pattern.compile( "\"translation\":\\[\"(.*?)\"\\]"); matcher = pattern.matcher(outputYouDao); if (matcher.find()) outputYouDao = matcher.group(1); youdaoTranslation.setText(outputYouDao); commonTextArea.setText(findCommonPart(outputBaidu, outputYouDao)); }); } private String translateUsingBaidu(String text) throws UnsupportedEncodingException { // 调用百度翻译API进行翻译 TransApi api = new TransApi("", ""); return api.getTransResult(text, "zh", "en"); } private String translateUsingYoudao(String text) throws NoSuchAlgorithmException { // 调用有道翻译API进行翻译 YouDaoAPI api = new YouDaoAPI("", ""); return api.getTransResult(text, "zh", "en"); } private String findCommonPart(String text1, String text2) { // 比较两个翻译结果,找出相同部分 String[] baidu = text1.split("[ ,.]"); String[] youdao = text2.split("[ ,.]"); StringBuilder common = new StringBuilder(); for (String a : baidu) { for (String b : youdao) { if (Objects.equals(a, b)) { common.append(a).append(" "); } } } return common.toString(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { TranslationDemo demo = new TranslationDemo(); demo.setVisible(true); }); } }

YouDaoAPI.java

import com.youdao.aicloud.translate.utils.AuthV3Util; import com.youdao.aicloud.translate.utils.HttpUtil; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; /** * 网易有道智云翻译服务api调用demo * api接口: https://openapi.youdao.com/api */ public class YouDaoAPI { private static String APP_KEY = ""; // 您的应用ID private static String APP_SECRET = ""; // 您的应用密钥 public YouDaoAPI(String appid, String securityKey) { APP_KEY = appid; APP_SECRET = securityKey; } public String getTransResult(String query, String from, String to) throws NoSuchAlgorithmException { // 添加请求参数 Map params = createRequestParams(query, from, to); // 添加鉴权相关参数 AuthV3Util.addAuthParams(APP_KEY, APP_SECRET, params); // 请求api服务 byte[] result = HttpUtil.doPost("https://openapi.youdao.com/api", null, params, "application/json"); return new String(result, StandardCharsets.UTF_8); } private static Map createRequestParams(String query, String from, String to) { return new HashMap() {{ put("q", new String[]{query}); put("from", new String[]{from}); put("to", new String[]{to}); }}; } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3