(text string)
| 59 | node.isKeywordEnd = true |
| 60 | } |
| 61 | func (sf *SensitiveFilter) Filter(text string) string { |
| 62 | if text == "" { |
| 63 | return text |
| 64 | } |
| 65 | |
| 66 | var ( |
| 67 | result strings.Builder |
| 68 | start int |
| 69 | position int |
| 70 | node = sf.root |
| 71 | ) |
| 72 | |
| 73 | for position < len(text) { |
| 74 | char, charWidth := utf8.DecodeRuneInString(text[position:]) |
| 75 | if char == utf8.RuneError { |
| 76 | // 如果字符解码失败,直接写入原始字节 |
| 77 | result.WriteByte(text[start]) |
| 78 | position++ |
| 79 | start = position |
| 80 | node = sf.root |
| 81 | continue |
| 82 | } |
| 83 | |
| 84 | // 跳过符号 |
| 85 | if isSymbol(char) { |
| 86 | // 如果当前节点是根节点,将符号加入结果,移动起始位置 |
| 87 | if node == sf.root { |
| 88 | result.WriteRune(char) |
| 89 | start += charWidth |
| 90 | } |
| 91 | // 移动当前检查位置 |
| 92 | position += charWidth |
| 93 | continue |
| 94 | } |
| 95 | |
| 96 | // 检查下级节点 |
| 97 | node = node.getSubNode(char) |
| 98 | if node == nil { |
| 99 | // 当前字符不在敏感词中,将起始字符加入结果 |
| 100 | result.WriteString(text[start : start+charWidth]) |
| 101 | // 移动起始位置和当前检查位置 |
| 102 | position = start + charWidth |
| 103 | start = position |
| 104 | // 重置节点到根节点 |
| 105 | node = sf.root |
| 106 | } else if node.isKeywordEnd { |
| 107 | // 发现敏感词,替换为 *** |
| 108 | result.WriteString("***") |
| 109 | // 移动起始位置和当前检查位置 |
| 110 | position += charWidth |
| 111 | start = position |
| 112 | // 重置节点到根节点 |
| 113 | node = sf.root |
| 114 | } else { |
| 115 | // 继续检查下一个字符 |
| 116 | position += charWidth |
| 117 | } |
| 118 | } |
no test coverage detected