wang-hao-jie
2021-10-19 e48043a2df9ca0c73fe18298bab3c4d42ca5c0c7
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package cn.exrick.xboot.core.common.utils;
 
import cn.exrick.xboot.core.common.exception.XbootException;
import cn.exrick.xboot.core.service.StopWordService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.WordTree;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
 
import java.util.List;
 
/**
 * @author exrick
 */
@Slf4j
public class StopWordsUtil {
 
    private static StopWordService stopWordService = SpringUtil.getBean(StopWordService.class);
 
    private StopWordsUtil() {
 
    }
 
    private static WordTree wordTree;
 
    public static WordTree getInstance() {
 
        if (wordTree == null) {
            // 初始加载数据
            wordTree = new WordTree();
            stopWordService.getAll().forEach(e -> wordTree.addWord(e.getTitle()));
        }
        return wordTree;
    }
 
    public static void addWord(String word) {
 
        getInstance().addWord(word);
    }
 
    public static void removeWord(String word) {
 
        getInstance().remove(word);
    }
 
    /**
     * 返回匹配的词
     * @param param
     * @return
     */
    public static String match(String param) {
 
        return getInstance().match(param);
    }
 
    /**
     * 检测到禁用词直接抛出异常
     * @param param
     * @return
     */
    public static void matchWord(String param) {
 
        if (StrUtil.isNotBlank(match(param))) {
            throw new XbootException("包含禁用词:" + param);
        }
    }
 
    /**
     * 返回所有匹配的词
     * @param param
     * @return
     */
    public static List<String> matchAll(String param) {
 
        return getInstance().matchAll(param);
    }
 
    /**
     * 将匹配词过滤为*
     * @param param
     * @return
     */
    public static String filter(String param) {
 
        return filter(param, "*");
    }
 
    /**
     * 自定义替换符号字符
     * @param param
     * @param replacement
     * @return
     */
    public static String filter(String param, String replacement) {
 
        for(String e : matchAll(param)){
            param = param.replaceAll(e, replacement);
        }
        return param;
    }
}