阿里云翻译使用

导入阿里云翻译包

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>alimt20181012</artifactId>
    <version>1.1.0</version>
</dependency>

代码 只请求一次接口返回所有翻译结果并且会把翻译结果存入本地文本,下次使用会先从文本获取,以便于更快的获取响应结果

package com.xxx;

import com.aliyun.alimt20181012.models.TranslateGeneralResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 阿里云翻译包
 * <dependency>
 * <groupId>com.aliyun</groupId>
 * <artifactId>alimt20181012</artifactId>
 * <version>1.1.0</version>
 * </dependency>
 */
public class AlibabaCloudTranslation {

    //默认id
    public static final String DEFAULT_ACCESS_KEY_ID = "你的id";

    //默认secret
    public static final String DEFAULT_ACCESS_KEY_SECRET = "你的secret";

    //中文
    public static final String ZH = "zh";

    //英文
    public static final String EN = "en";

    //设置格式类型
    public static final String TEXT = "text";

    // 访问的域名
    public static final String MT_ALIYUNCS_COM = "mt.aliyuncs.com";

    //设置场景为一般
    public static final String GENERAL = "general";

    public static final String EXCEPTION_MSG = "翻译失败:[阿里云的id或密码错误][网络异常]";
    public static final char CHARACTER_UNDERLINE = '_';
    public static final char NULL_CHARACTER = ' ';
    public static final String DELIMITER_COMMA = ",";
    public static final String SEMICOLON = ";";

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId     阿里云密钥id
     * @param accessKeySecret 阿里云密钥密码
     * @return Client 客户端
     * @throws Exception 初始化客户端异常
     */
    public static com.aliyun.alimt20181012.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填,AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = MT_ALIYUNCS_COM;
        return new com.aliyun.alimt20181012.Client(config);
    }


    /**
     * 获取翻译结果  如果密钥和密码为空,则默认使用这个特定的id与密码,但有可能失效
     *
     * @param text            翻译内容
     * @param accessKeyId     阿里云密钥id
     * @param accessKeySecret 阿里云密钥密码
     * @return String 翻译结果
     */
    public static String getResults(String text, String accessKeyId, String accessKeySecret) {
        if (StringUtils.isEmpty(text)) {
            return "";
        }

        // 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
        com.aliyun.alimt20181012.Client client;
        try {
            if (StringUtils.isAllEmpty(accessKeyId, accessKeySecret)) {
                client = AlibabaCloudTranslation.createClient(DEFAULT_ACCESS_KEY_ID, DEFAULT_ACCESS_KEY_SECRET);
            } else client = AlibabaCloudTranslation.createClient(accessKeyId, accessKeySecret);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        com.aliyun.alimt20181012.models.TranslateGeneralRequest translateGeneralRequest = new com.aliyun.alimt20181012.models.TranslateGeneralRequest()
                .setFormatType(TEXT)
                .setSourceLanguage(ZH)
                .setTargetLanguage(EN)
                .setSourceText(text)
                .setScene(GENERAL);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        TranslateGeneralResponse translateGeneralResponse;
        try {
            // 获取响应
            translateGeneralResponse = client.translateGeneralWithOptions(translateGeneralRequest, runtime);
        } catch (Exception error) {
            throw new RuntimeException(EXCEPTION_MSG);
        }
        return translateGeneralResponse.getBody().getData().getTranslated();
    }

    /**
     * 请求一次接口获取所有文本的翻译,通过map映射  map<文本,翻译结果> 并返回
     *
     * @param textList        翻译内容集合
     * @param accessKeyId     阿里云密钥id
     * @param accessKeySecret 阿里云密钥密码
     * @return LinkedHashMap<文本, 翻译结果>
     */
    public static Map<String, String> getResultsMap(List<String> textList, String accessKeyId, String accessKeySecret) {
        //读取文件 没有会创建
        String filePath = "C:\\translateAFile.txt";
        Map<String, String> resultsMap = readLocalFile(filePath);
        for (String key : textList) {
            String value = resultsMap.get(key);
            if (value == null) {
                value = getResults(key, accessKeyId, accessKeySecret);
                //去除特殊字符串
                value = removeSpecialCharacters(value);
                resultsMap.put(key, value);
            }
        }
        StringBuilder sb = new StringBuilder();
        resultsMap.forEach((x, y) -> {
            sb.append(x).append(SEMICOLON).append(y).append("\n");
        });
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) {
            // 将StringBuilder的内容写入文件
            bw.write(sb.toString());
            bw.newLine();
        } catch (IOException e) {
            System.err.println("Error writing file: " + e.getMessage());
        }
        return resultsMap;
    }

    /**
     * 读取本地文件 没有则创建
     */
    public static Map<String, String> readLocalFile(String filePath) {
        Map<String, String> dataMap = new HashMap<>();
        Path file = Path.of(filePath);
        try (BufferedReader br = Files.exists(file) ? new BufferedReader(new FileReader(filePath)) : null) {
            if (br == null) {
                // 如果文件不存在,创建它并写入标题行
                BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
                bw.close();
            } else {
                String line;
                while ((line = br.readLine()) != null) {
                    // 使用 ; 隔开
                    String[] parts = line.split(SEMICOLON);
                    //检查 parts的长度
                    if (parts.length == 2) {
                        // 把第一个元素设置为key  第二个元素设置为value
                        dataMap.put(parts[0], parts[1]);
                    } else {
                        System.err.println("无效的行格式:" + line);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("读取/写入文件时出错: " + e.getMessage());
        }
        return dataMap;
    }

    /**
     * 去除字符串的特殊字符串
     *
     * @param text 字符串
     * @return String 字符串
     */
    public static String removeSpecialCharacters(String text) {
        return text.replaceAll("[\n`~!,#$@%^&*()+=|{}':;\\[\\].<>/?!¥…()—【】‘;:”“’。,、?]", "");
    }

    /**
     * 翻译并改为大写 空格变为下划线  to upper case with underscore ->  TO_UPPER_CASE_WITH_UNDERSCORE 格式
     *
     * @param text 字符串
     * @return String 字符串
     */
    public static String toUpperCaseWithUnderscore(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == NULL_CHARACTER) {
                result.append(CHARACTER_UNDERLINE);
            } else {
                result.append(Character.toUpperCase(c));
            }
        }
        return result.toString();
    }

    /**
     * 字符串改为 大驼峰格式  to camel case -> ToCamelCase
     *
     * @param text 字符串
     * @return String 字符串
     */
    public static String toCamelCase(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        StringBuilder result = new StringBuilder();
        return getString(text, result);
    }

    public static String getString(String text, StringBuilder result) {
        boolean capitalizeNext = true;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == NULL_CHARACTER || c == CHARACTER_UNDERLINE) {
                capitalizeNext = true;
            } else if (capitalizeNext) {
                result.append(Character.toUpperCase(c));
                capitalizeNext = false;
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }

    /**
     * 下划线转大驼峰 TEST_ENUM -> TestEnum
     *
     * @param text 字符串
     * @return String 字符串
     */
    public static String toUnderCase(String text) {
        if (text == null || text.isEmpty()) {
            return text;
        }
        text = text.toLowerCase();
        StringBuilder result = new StringBuilder();
        return getString(text, result);
    }

    /**
     * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
     * 例如:HelloWorld Hello-World -> HELLO_WORLD
     *
     * @param text 转换前的驼峰式命名的字符串
     * @return 转换后下划线大写方式命名的字符串
     */
    public static String underscoreName(String text) {
        StringBuilder result = new StringBuilder();
        if (text != null && !text.isEmpty()) {
            //是否存在特殊字符
            Pattern compile = Pattern.compile(".*[ _\\-`~!@#$%^&*()+=|{}':;,\\[\\].<>/?!¥…()—【】‘;:”“’。,、?\\n\\r\\t].*");
            Matcher matcher = compile.matcher(text);
            if (matcher.matches()) {
                // 将所有字符转换为小写 将所有的非字母字符替换为空格 将所有连续的空格替换为一个空格 将所有空格替换为下划线 将所有字符转换为大写
                text = text.toLowerCase().replaceAll("[^a-z]", " ").replaceAll("\\s+", " ").replaceAll(" ", "_").toUpperCase();
                return text;
            }
            // 将第一个字符处理成大写
            result.append(text.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < text.length(); i++) {
                String s = text.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值