Golang
主页 > 脚本 > Golang >

golang敏感词过滤的实现

2023-01-05 | 佚名 | 点击:

用golang写了敏感词过滤的工具,主要用来检测用户昵称中是否存在敏感词,同时提供剔除转移字符的功能。

可以先将敏感词库存放在一个map中,敏感词可以参考这里:https://github.com/fwwdn/sensitive-stop-words

将map和昵称传入,程序会检查昵称的每一个子串,判断是否在map敏感词库中。复杂度O(len(name)^2)

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

package util

  

import (

    "github.com/pkg/errors"

    "strings"

  

)

  

type filter struct {

    data        string

    maxLimitLen int

}

  

func NewKeywordFilter(str string, maxLimitLen int) (*filter, error) {

    if len(str) > maxLimitLen {

        return nil, errors.Errorf("长度:%d,不能超过:%d", len(str), maxLimitLen)

    }

    return &filter{

        data:        str,

        maxLimitLen: maxLimitLen,

    }, nil

}

  

func (f *filter) GetData() string {

    return f.data

}

  

func (f *filter) FilterKeywords(keywords map[string]bool) (err error) {

    if keywords == nil {

        return

    }

    for i := 0; i < len(f.data); i++ {

        for j := i + 1; j <= len(f.data); j++ {

            subStr := f.data[i:j]

            if _, found := keywords[subStr]; found {

                err = errors.Errorf("昵称违规,建议修改")

            }

        }

    }

    return

}

  

func (f *filter) TrimAllCharset(ch []string) (err error) {

    if ch == nil {

        return

    }

    for _, c := range ch {

        f.data = strings.Replace(f.data, c, "", -1)

    }

    if len(f.data) == 0 {

        err = errors.New("剔除相关转移字符后,数据长度为0.")

        return

    }

    return

}

原文链接:https://blog.csdn.net/liyunlong41/article/details/85160209
相关文章
最新更新