-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathFilterTrie.lua
More file actions
56 lines (51 loc) · 1.54 KB
/
Copy pathFilterTrie.lua
File metadata and controls
56 lines (51 loc) · 1.54 KB
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
-- 说明: 类似王者荣耀那种敏感词替换, 目前只支持单个词, 带&词替换等待后续扩展
require("PreLoad")
local Trie = require("Trie")
local FilterTrie = class("FilterTrie")
function FilterTrie:ctor(trie)
self._trie = Trie.New()
self._trie:CopyConstruction(trie)
self._onceContex = nil
self:__Init()
end
function FilterTrie:__Init()
self._trie:SetExtCheckFunc(function(i, j)
if not self._onceContex then
self._onceContex = {}
end
table.insert(self._onceContex, i)
table.insert(self._onceContex, j)
return false -- 返回false视为没有匹配到, 继续迭代
end)
end
-- 返回值1替换后的newChars,和参数是同一数组,是浅拷贝; 返回值2是否是敏感词被替换过
function FilterTrie:FilterChars(chars)
self._onceContex = nil
self._trie:CheckCharArrayMatched(chars)
local newChars = chars
local matched = false -- 默认没有匹配到
if self._onceContex then
-- 有匹配到
matched = true
local count = #self._onceContex / 2
for i=1,count do
local v1 = self._onceContex[2*i-1]
local v2 = self._onceContex[2*i]
for j=v1,v2 do
chars[j] = "*" -- 默认替换为‘*’
end
end
end
return newChars, matched
end
-- 返回值1替换后的字符串, 返回值2是否被替换过(如果存在敏感词就会被替换掉)
function FilterTrie:FilterText(text)
local chars = string.ConvertToCharArray(text)
local newChars, matched = self:FilterChars(chars)
local newText = text
if matched then
newText = table.concat(newChars)
end
return newText, matched
end
return FilterTrie