导入阿里云翻译包
<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;
public class AlibabaCloudTranslation {
public static final String DEFAULT_ACCESS_KEY_ID = "你的id";
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 = ";";
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()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = MT_ALIYUNCS_COM;
return new com.aliyun.alimt20181012.Client(config);
}
public static String getResults(String text, String accessKeyId, String accessKeySecret) {
if (StringUtils.isEmpty(text)) {
return "";
}
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();
}
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))) {
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);
if (parts.length == 2) {
dataMap.put(parts[0], parts[1]);
} else {
System.err.println("无效的行格式:" + line);
}
}
}
} catch (IOException e) {
System.err.println("读取/写入文件时出错: " + e.getMessage());
}
return dataMap;
}
public static String removeSpecialCharacters(String text) {
return text.replaceAll("[\n`~!,#$@%^&*()+=|{}':;\\[\\].<>/?!¥…()—【】‘;:”“’。,、?]", "");
}
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();
}
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();
}
public static String toUnderCase(String text) {
if (text == null || text.isEmpty()) {
return text;
}
text = text.toLowerCase();
StringBuilder result = new StringBuilder();
return getString(text, result);
}
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();
}
}