--[[ ac_automaton.lua —— 纯 Lua 实现的 AC 自动机(Aho–Corasick Automaton) 干什么:给一堆关键词,一次扫描找出长文本里所有关键词的出现位置。 怎么用: local AC = require("ac_automaton") local ac = AC.buildFrom({ "感冒", "药", "感冒药" }) for _, hit in ipairs(ac:find("我感冒了")) do print(hit.word, hit.start, hit.finish) end 直接运行本文件看示例: lua ac_automaton.lua 注意: * 字符串按“字节”匹配,所以 start / finish 是字节下标,不是“第几个字”。 中文在 UTF-8 里一个字占 3 个字节。 * build() 之后不要再用 insert(),要加词就重新 buildFrom()。 ]] local AC = {} AC.__index = AC --============================================================ -- 一、建树 --============================================================ -- 创建一个空自动机(只有根节点) function AC.new() local self = setmetatable({}, AC) self.children = {} -- children[节点][字节] = 子节点编号 self.fail = {} -- fail[节点] = 失配后跳到的节点 self.output = {} -- output[节点] = 在这里结尾的所有关键词 self.count = 0 -- 已分配的节点个数(根节点编号固定是 1) self:newNode() -- 先把根建出来 self.fail[1] = 1 -- 根的 fail 指回自己,方便循环里统一处理 return self end -- 分配一个新节点,返回它的编号 function AC:newNode() self.count = self.count + 1 local id = self.count self.children[id] = {} self.fail[id] = 1 -- 默认都退回根,build 时再改 self.output[id] = {} return id end -- 插入一个关键词:沿着已有的路走,走不通就新开一个节点 -- -- 注意“从根出发”是必须的:扫描时指针永远从根开始, -- 所以每个词都得有一条从根能走通的完整路径。 -- 和别的词共享的只有“前缀”,不是“子串”。 -- (“药剂” 和 “感冒药剂” 的后缀关系由 fail 指针负责,见 build) function AC:insert(word) if word == nil or word == "" then return end -- 空词没有意义,跳过 local node = 1 -- 从根出发 for i = 1, #word do local b = word:byte(i) -- 逐个字节走,对 UTF-8 安全 local nxt = self.children[node][b] if not nxt then nxt = self:newNode() self.children[node][b] = nxt end node = nxt end -- 到达词尾的节点,插一面“小旗” local outs = self.output[node] outs[#outs + 1] = { word = word, len = #word } end -- 构建 fail 指针(广度优先,一层一层算) -- -- 拿模式 { he, she, his, hers } 走一遍,每一步大概是这个意思: -- -- 1) 第一层的 h、s:没有更短的后缀可用,fail 都指回根。 -- 2) 出队 h,处理它的边 'e' → he: -- 从 fail(h) = root 找 'e',root 没有 'e' 边 → fail(he) = root。 -- 3) 出队 sh,处理它的边 'e' → she: -- 从 fail(sh) = h 找 'e',h 有 'e' 边 → fail(she) = he。 -- 顺手把 he 的榜单 {he} 抄给 she,于是 she 的榜单变成 {she, he}。 -- 4) 出队 hi,处理它的边 's' → his: -- 从 fail(hi) = root 找 's',root 有 's' 边(指向 s)→ fail(his) = s。 -- 5) 出队 her,处理它的边 's' → hers: -- 从 fail(her) = root 找 's',root 有 's' 边 → fail(hers) = s。 function AC:build() local queue, head, tail = {}, 1, 0 -- 第一步:根的孩子们,fail 一律指向根 for _, child in pairs(self.children[1]) do self.fail[child] = 1 tail = tail + 1 queue[tail] = child end while head <= tail do local node = queue[head] head = head + 1 for b, child in pairs(self.children[node]) do -- 从“父亲的 fail”开始,找一个也有 b 这条出边的祖先 local f = self.fail[node] while f ~= 1 and not self.children[f][b] do f = self.fail[f] end local target = self.children[f][b] if target and target ~= child then self.fail[child] = target -- 找到了,这就是最长可复用后缀 else self.fail[child] = 1 -- 找不到,退回根 end -- 把 fail 节点上的命中名单抄一份过来。 -- 这样扫描时只看当前节点就够了,不用顺着 fail 链爬。 local src, dst = self.output[self.fail[child]], self.output[child] for i = 1, #src do dst[#dst + 1] = src[i] end tail = tail + 1 queue[tail] = child end end end -- 一步到位:用一串关键词直接造出一个建好的自动机 function AC.buildFrom(words) local ac = AC.new() for i = 1, #words do ac:insert(words[i]) end ac:build() return ac end --============================================================ -- 二、拿它干活 --============================================================ -- 在 text 里找出所有命中,返回 { word=, start=, finish= } 的数组(字节下标) function AC:find(text) local hits = {} local node = 1 for i = 1, #text do local b = text:byte(i) -- 没路了就沿 fail 往回退,退到有路或者退回根为止 while node ~= 1 and not self.children[node][b] do node = self.fail[node] end node = self.children[node][b] or 1 -- 当前节点上的名单就是此刻全部命中(build 时已经抄好了) local outs = self.output[node] for k = 1, #outs do local out = outs[k] hits[#hits + 1] = { word = out.word, start = i - out.len + 1, finish = i, } end end return hits end -- 只问“有没有命中”,一发现就停 function AC:contains(text) local node = 1 for i = 1, #text do local b = text:byte(i) while node ~= 1 and not self.children[node][b] do node = self.fail[node] end node = self.children[node][b] or 1 if #self.output[node] > 0 then return true end end return false end -- 把命中的部分替换成 mask(默认 "*")。 -- 同一位置有多个命中时,优先用最长的那个(比如优先遮“感冒药”而不是“感冒”)。 -- mask 建议用单字节字符,否则长度对不上。 function AC:filter(text, mask) mask = mask or "*" local hits = self:find(text) table.sort(hits, function(a, b) if a.start ~= b.start then return a.start < b.start end return a.finish > b.finish -- 同起点,长的排前面 end) local buf, cursor = {}, 1 for i = 1, #hits do local h = hits[i] if h.start >= cursor then -- 跳过和已替换区间重叠的 buf[#buf + 1] = text:sub(cursor, h.start - 1) buf[#buf + 1] = mask:rep(h.finish - h.start + 1) cursor = h.finish + 1 end end buf[#buf + 1] = text:sub(cursor) return table.concat(buf) end --============================================================ -- 三、自测 + 示例 --============================================================ local function selftest() -- 教科书例子:模式 {he, she, his, hers},文本 "ushers" local ac = AC.buildFrom({ "he", "she", "his", "hers" }) local words = {} for _, hit in ipairs(ac:find("ushers")) do words[#words + 1] = hit.word .. "@" .. hit.start end table.sort(words) local got = table.concat(words, ",") assert(got == "he@3,hers@3,she@2", "ushers 匹配错误,实际是: " .. got) -- 中文:一个词是另一个词的后缀,两个都要报出来 local cn = AC.buildFrom({ "感冒", "药", "感冒药" }) local text = "我感冒了,要吃药,吃了感冒药就好" local counter = {} for _, hit in ipairs(cn:find(text)) do counter[hit.word] = (counter[hit.word] or 0) + 1 end assert(counter["感冒"] == 2, "“感冒”应有 2 次,实际 " .. tostring(counter["感冒"])) assert(counter["药"] == 2, "“药”应有 2 次,实际 " .. tostring(counter["药"])) assert(counter["感冒药"] == 1, "“感冒药”应有 1 次,实际 " .. tostring(counter["感冒药"])) -- 打码:中文一个字 3 字节,所以遮罩也是 3 个 "*" assert(cn:filter("我感冒了", "*") == "我******了", "filter 结果不对") assert(cn:contains("我感冒了") == true) assert(cn:contains("我没病") == false) print("自测全部通过 ✔") end local function demo() print("== 英文:在 ushers 里找 he / she / his / hers ==") local ac = AC.buildFrom({ "he", "she", "his", "hers" }) for _, hit in ipairs(ac:find("ushers")) do print(string.format(" %-5s 位置 %d..%d", hit.word, hit.start, hit.finish)) end print("") print("== 中文:敏感词打码 ==") local cn = AC.buildFrom({ "感冒", "药", "感冒药" }) local text = "我感冒了,要吃药,吃了感冒药就好" print(" 原文: " .. text) print(" 打码: " .. cn:filter(text, "*")) print(" 命中:") for _, hit in ipairs(cn:find(text)) do print(string.format(" %-9s 字节位置 %d..%d", hit.word, hit.start, hit.finish)) end print("") selftest() end -- 直接 `lua ac_automaton.lua` 运行时,main chunk 的 ... 是 nil,跑示例; -- 被 require 时 ... 是模块名,只返回模块。 if ... == nil then demo() end return AC