lua 文件读写处理(操做敏感词库)

       最近须要给游戏作一个敏感词新系统,我采用的方法是比较经常使用的DFA(肯定有穷状态机)算算法

法,先不讲算法,而这种算法的实现须要一个相应的敏感词库。编码

      我拿到了词库后发现词库中大概有8000+个词,其中包括不少重复的,还有不少有着头包含关lua

系的词;spa

  什么是头包含词呢? 看以下例子:code

  咱们知道在DFA算法读取敏感词后若是存在这种状况:blog

  词1: "ab"  词2:  "abc" 索引

  在读取以后“ ab “这个敏感词就会不复存在而被abc覆盖掉, 而咱们游戏须要对敏感词进行的游戏

操做不是以其余字符(如 * *)代替句子中的敏感词而是若是判断出句子中含有敏感词,则没法发ip

出。因此,若是 “ab” 已是敏感词了,“abc”就没有必要出如今敏感词库中了因此我须要将敏感字符串

词库中的

  1. 相同的词只留下一个 

  2. 删除头包含其余敏感词的敏感词

  可是现有的敏感词库中有8000+ 个词我不可能一个个去找,因此我就想到了利用现有的lua io

文件库对原先的敏感词库进行处理这样能够节省太多的时间 代码以下

local function getNewWord() local wordsDataInput  = {} local wordsDataOutput = {} -- 读取文件
    -- 以只读方式打开文件
    local file_input = io.open("sensitive_words_input.txt", "r") -- 设置默认输入文件为 test.lua
    io.input(file_input) -- 逐行读取文件
    local string_l = file_input:read("*l") while(string_l ~= nil) do
        table.insert(wordsDataInput, string_l) string_l = file_input:read("*l") end
    io.close(file_input) -- 写入文件
    -- 以只写方式打开文件
    local file_output = io.open("sensitive_words.txt", "a") -- 设置默认输出文件为
    io.output(file_output) -- 对数据进行处理
    -- 若是有头包含
    local function ifIsHeadInTable(str) for i = 1, #wordsDataInput do
            local startIndex, endIndex = string.find(wordsDataInput[i], str) if startIndex ~= nil and endIndex ~= nil then
                -- 若是find到头索引为1,尾索引不为字符串长度则能够认定为是头包含关系
                if startIndex == 1 and endIndex ~= string.len(wordsDataInput[i]) then wordsDataInput[i] = "\n"
                end
            end
        end    
    end 
    
    -- 是否已经有相同的
    local function isHasSameInTable(str) if not wordsDataOutput or not next(wordsDataOutput) then return false end

        for key, value in ipairs(wordsDataOutput) do
            if value == str then
                return true
            end
        end

        return false
    end

    -- 先剔除头包含
    for key, value in pairs(wordsDataInput) do ifIsHeadInTable(value) end

    -- 再剔除相同的
    for key, value in ipairs(wordsDataInput) do
        if not isHasSameInTable(value) then
            table.insert(wordsDataOutput, value) end
    end

    for index, word in pairs(wordsDataOutput) do
        io.write(word.."\n") end
    io.close(file_output) end

 

    

  操做后的文件少了整整4000个词,差很少35kb,这样加载词库须要的空间和时间都大大减小。可是要注意的是lua对文件的操做都是以UTF-8编码来的,若是是其余编码的文件就不能用了。