翻译功能,根据传入的字符串翻译数据库中的英文字段
翻译功能
/**
* 翻译词根,根据模型那边传入的中文字符串参数,翻译出对应的英文词根。参数可能为两种情况单个字符串,多个字符串用下划线连接。
* 采用最大匹配算法,尽可能匹配最大长度的数据翻译。
*
* @param input
* @return
*/
@Override
public String translate(String input) {
Map map = new HashMap();
input = input.replace(" ","");
DsUser user = DsAuthService.getLoginUser();
//查询所有的词根
List<EtInfo> etInfoList = etInfoMapper.selectList(new LambdaQueryWrapper<EtInfo>()
.eq(EtInfo::getTenantId, user.getTenantId())
.eq(EtInfo::getIsDelete, Boolean.FALSE));
//将词根以{中文词根,英文词根}(EtymaCnNameAnother这个字段在数据库存放以逗号隔开的字符串存放,所以需要遍历依次存放)放入map,方便下面进行判断是否存在这个中文词根
for (EtInfo etInfo : etInfoList) {
map.put(etInfo.getEtymaCnName(), etInfo.getEtyma());
if (StringUtils.isNotEmpty(etInfo.getEtymaCnNameAnother())) {
String[] split = etInfo.getEtymaCnNameAnother().split(",");
for (String s : split) {
map.put(s, etInfo.getEtyma());
}
}
}
//匹配翻译词根
String result = this.positiveSplit(map, input, 10);
//翻译结果可能出现一些问题,下面处理一下
if (result.endsWith("_")) {
result = result.substring(0, result.length() - 1);
}
if (result.startsWith("_")) {
result = result.substring(1);
}
result = result.replace("___", "_")
.replace("__", "_");
return result;
}
/**
* 以下划线拼接各个词根
* @param input 前端传的字符串参数
* @param maxSize 数据库最长字符位数
* @return
*/
private String positiveSplit(Map map,String input, int maxSize) {
int length = input.length();
//字符串转为字符数组
char[] inputChar = input.toCharArray();
//拼接结果字符串
StringBuilder result = new StringBuilder();
for (int i = 0; i < length; i++) {
positiveOver = 0;
String sb = this.toStr(map,inputChar, i, maxSize );
i = i + positiveOver;
if (map.containsKey(sb)) {
result.append("_" + map.get(sb) + "_");
} else {
result.append(sb);
}
}
return result.toString();
}
/**
* 返回map包含的最大位数词根
* @param inputChar 前端字符串参数转化的字符数组
* @param start 根据字符串参数循环的长度传入的次数
* @param maxSize 数据库里的中文数据的最大长度
* @return
*/
private String toStr(Map map,char[] inputChar, int start, int maxSize) {
int num2 = maxSize;
out:
for (int j = 0; j < maxSize; j++) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num2; i++) {
if (start + i < inputChar.length) {
sb.append(inputChar[start + i]);
} else {
num2--;
j--;
continue out;
}
}
if (map.containsKey(sb.toString())) {
positiveOver = num2 - 1;
return sb.toString();
}
num2--;
}
return String.valueOf(inputChar[start]);
}