TangCheng
2025-02-28 d787e447e95c7b897c2cc9c0e832f8d2e5084934
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.smtaiserver.smtaiserver.javaai.ast;
 
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
 
import com.smtservlet.util.SMTStatic;
 
public class ASTQuestionReplace 
{
    public Pattern                _patQuestion;
    public Pattern                _patReplace;
    public Map<String, Map<String, String>>     _mapGroupType2Question2Replace;
    private static Logger                     _logger = LogManager.getLogger(ASTQuestionReplace.class);
    
    public ASTQuestionReplace(String sPatQuestion, String sPatReplace, Map<String, Map<String, String>> mapGroupType2Question2Replace)
    {
        _patQuestion = Pattern.compile(sPatQuestion);
        _patReplace = Pattern.compile(sPatReplace);
        _mapGroupType2Question2Replace = mapGroupType2Question2Replace;
    }
    
    public String replaceQuestion(String groupType, String question)
    {
        if(SMTStatic.isNullOrEmpty(question))
            return "";
        
        String curPatText = "";
        try
        {
            Map<String, String> mapQuestion2Replace = _mapGroupType2Question2Replace.get(groupType);
            
            if(mapQuestion2Replace == null)
                return question;
            
            Set<String> setExists = new HashSet<>();
            
            // 记录已经被替换后的文字
            curPatText = _patReplace.pattern();
            Matcher matcher = _patReplace.matcher(question);
            while(matcher.find())
            {
                setExists.add(matcher.group());
            }
            
            // 替换文字
            String result = SMTStatic.replaceRegexText(question, _patQuestion,  match ->
            {
                // 如果替换的文字没在字典表里则忽略
                String replace = mapQuestion2Replace.get(match);
                if(SMTStatic.isNullOrEmpty(replace))
                    return match;
                
                // 如果被替换的文字已经存在再问题中则忽略
                if(setExists.contains(replace))
                    return match;
                
                return replace;
            });
            
            return result;
        }
        catch(Exception ex)
        {
            _logger.fatal("replaceQuestion exception : [" + curPatText + "]=>[" + question + "]", ex);
            return question;
        }
    }
}