注意:需搭配标题二的腾讯翻译工具使用
一-1、翻译标签文本工具
package org.springblade.common.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TencentTranslationForHTML {
public static void main(String[] args) {
String htmlContent = "<div style=\"text-align:center\"><img src=\"http://192.168.0.137:8999/machine/upload/image/20250208/32551087576762.jpg\" alt=\"图片 alt\" width=\"350\" height=\"auto\" data-align=\"center\"></div><p style=\"text-align: center\">下料工序后的加工件</p>";
try {
String translatedHtml = translateHTML(htmlContent);
System.out.println(translatedHtml);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String translateHTML(String html) throws com.tencentcloudapi.common.exception.TencentCloudSDKException {
// 匹配 HTML 标签
Pattern tagPattern = Pattern.compile("<[^>]+>");
Matcher tagMatcher = tagPattern.matcher(html);
// 存储标签位置和内容
List<int[]> tagPositions = new ArrayList<>();
while (tagMatcher.find()) {
tagPositions.add(new int[]{tagMatcher.start(), tagMatcher.end()});
}
// 提取文本内容进行翻译
List<String> textParts = new ArrayList<>();
int lastEnd = 0;
for (int[] position : tagPositions) {
String textPart = html.substring(lastEnd, position[0]);
if (!textPart.isEmpty()) {
textParts.add(textPart);
}
lastEnd = position[1];
}
String remainingText = html.substring(lastEnd);
if (!remainingText.isEmpty()) {
textParts.add(remainingText);
}
// 调用腾讯翻译 API 翻译文本
List<String> translatedParts = new ArrayList<>();
for (String text : textParts) {
// String translated = translateText(text);
String translated = TencentTranslationUtil.getText(text,"zh","en");
translatedParts.add(translated);
}
// 重新组合翻译后的文本和 HTML 标签
StringBuilder result = new StringBuilder();
int textPartIndex = 0;
lastEnd = 0;
for (int[] position : tagPositions) {
int start = position[0];
int end = position[1];
if (start > lastEnd) {
result.append(translatedParts.get(textPartIndex++));
}
result.append(html, start, end);
lastEnd = end;
}
if (lastEnd < html.length()) {
result.append(translatedParts.get(textPartIndex));
}
return result.toString();
}
}
一-2、翻译json工具
package org.springblade.common.utils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
public class TencentTranslationForJson {
public static void main(String[] args) {
String jsonStr = "[{\"col1\":\"设备名称及数量\",\"col2\":\"铝切机、切管机\",\"$cellEdit\":false,\"$index\":0},{\"col1\":\"最大日产量\",\"col2\":\"10000 件\",\"$cellEdit\":false,\"$index\":1},{\"col1\":\"工人数量\",\"col2\":\"5 人\",\"$cellEdit\":false,\"$index\":2}]";
extracted(jsonStr, "en", "zh");
}
public static void extracted(String jsonStr, String sourceLang, String targetLang) {
// 判断是否为有效的 JSON
if (isValidJson(jsonStr)) {
// 解析 JSON 字符串为 JsonArray
Gson gson = new Gson();
JsonArray jsonArray = gson.fromJson(jsonStr, JsonArray.class);
// 遍历 JSON 数组,提取需要翻译的文本
List<String> textsToTranslate = new ArrayList<>();
for (JsonElement element : jsonArray) {
JsonObject obj = element.getAsJsonObject();
for (String key : obj.keySet()) {
if (obj.get(key).isJsonPrimitive() && obj.get(key).getAsJsonPrimitive().isString()) {
textsToTranslate.add(obj.get(key).getAsString());
}
}
}
// 调用腾讯翻译 API 进行翻译
List<String> translatedTexts = translateTexts(textsToTranslate, sourceLang, targetLang);
// 将翻译结果回填到 JSON 中
int index = 0;
for (JsonElement element : jsonArray) {
JsonObject obj = element.getAsJsonObject();
for (String key : obj.keySet()) {
if (obj.get(key).isJsonPrimitive() && obj.get(key).getAsJsonPrimitive().isString()) {
obj.addProperty(key, translatedTexts.get(index));
index++;
}
}
}
// 输出翻译后的 JSON
System.out.println(gson.toJson(jsonArray));
} else {
System.out.println("输入的字符串不是有效的 JSON,不进行翻译。");
}
}
private static boolean isValidJson(String jsonStr) {
jsonStr = jsonStr.trim();
if (jsonStr.isEmpty()) {
return false;
}
// 判断是否以 '{' 或 '[' 开头,以 '}' 或 ']' 结尾
if ((jsonStr.startsWith("{") && jsonStr.endsWith("}")) || (jsonStr.startsWith("[") && jsonStr.endsWith("]"))) {
try {
int depth = 0;
boolean inString = false;
for (int i = 0; i < jsonStr.length(); i++) {
char c = jsonStr.charAt(i);
if (inString) {
if (c == '\\') {
i++; // 跳过转义字符后的字符
} else if (c == '"') {
inString = false;
}
} else {
if (c == '"') {
inString = true;
} else if (c == '{' || c == '[') {
depth++;
} else if (c == '}' || c == ']') {
depth--;
if (depth < 0) {
return false; // 括号不匹配
}
}
}
}
return depth == 0 && !inString; // 括号完全匹配且不在字符串中结束
} catch (Exception e) {
return false;
}
}
return false;
}
private static List<String> translateTexts(List<String> texts, String sourceLang, String targetLang) {
List<String> translatedTexts = new ArrayList<>();
for (String text : texts) {
String translatedText = TencentTranslationUtil.getText(text, sourceLang, targetLang);
translatedTexts.add(translatedText);
}
return translatedTexts;
}
}
二、腾讯翻译api调用
package org.springblade.common.utils;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import org.springblade.core.tool.utils.Func;
import java.lang.reflect.Field;
/**
* @project
* @Classname
* @Description
* @Author:
* @CreateTime:
*/
public class TencentTranslationUtil {
private final static String secretId = "自己的";
private final static String secretKey = "自己的";
private final static String params = "isMenu,type,icon";
private final TmtClient client;
/**
* 翻译
*
* @param text 需要翻译的文本
* @param sourceLang 来源语言
* @param targetLang 目标语言
* @return
*/
public static String getText(String text, String sourceLang, String targetLang) {
TencentTranslationUtil translationClient = new TencentTranslationUtil(secretId, secretKey);
if (Func.isEmpty(text.trim())) {
return text;
}
try {
return translationClient.translateText(text, sourceLang, targetLang);
} catch (TencentCloudSDKException e) {
System.err.println("腾讯翻译错误 = " + e.getMessage());
}
return "";
}
/**
* secretId,secretKey id和密钥
*/
public TencentTranslationUtil(String secretId, String secretKey) {
Credential cred = new Credential(secretId, secretKey);
client = new TmtClient(cred, "ap-beijing");
}
/**
* secretId,secretKey id和密钥
* region 地域
*/
public TencentTranslationUtil(String secretId, String secretKey, String region) {
Credential cred = new Credential(secretId, secretKey);
client = new TmtClient(cred, region);
}
/**
* text 需要翻译的文本
* sourceLang 翻译文本的语种
* targetLang 目标语种
*/
public String translateText(String text, String sourceLang, String targetLang) throws TencentCloudSDKException {
TextTranslateRequest req = new TextTranslateRequest();
req.setSourceText(text);
req.setSource(sourceLang);
req.setTarget(targetLang);
req.setProjectId(0L);
TextTranslateResponse resp = client.TextTranslate(req);
return resp.getTargetText();
}
/**
* 翻译对象每个的字段并重新给对象赋值
* @param obj
* @param sourceLang
* @param targetLang
*/
public static void translateFields(Object obj, String sourceLang, String targetLang) {
if (!sourceLang.equals(targetLang)) {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true); // 允许访问私有字段
Object value = field.get(obj);
//值不为空,且是字符串,不包含透明度,值非纯数字
if (Func.isNotEmpty(value) && value instanceof String
&& !((String) value).contains("div") && !((String) value).contains("opacity") && !isNumeric(((String) value))) {
if (!params.contains(field.getName())) {
Thread.sleep(150);
String text = TencentTranslationUtil.getText((String) value, sourceLang, targetLang);
if (Func.isNotEmpty(text)) {
field.set(obj, text); // 重新赋值翻译后的文本
} else {
field.set(obj, Func.toStr(value)+"(翻译失败)"); // 重新赋值翻译后的文本
}
}
}
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
// System.out.println(getText("{\"opacity\":1,\"x\":\"67.5px\",\"y\":\"53px\",\"rotate\":0}","en","zh-TW"));
// System.out.println("args = " + isNumeric("1s"));
if(!isNumeric("1")){
System.out.println("翻译");
}
}
/**
* 判断字符串是否是纯数字
* @param str
* @return
*/
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?");
}
}