背景描述

编程或者文档处理过程, 经常遇到需要将一个单词修改为另外一个单词的情况, 例如 命名为 shall 修改 为 should。

使用工具实现, 则比较方便,不容易出错, 解放双手。

需求规格

对于某个文件夹中的所有文本文件(txt), 将某个单词替换为目标单词。

实现思路

对于替换的单词映射, 在配置文件config.lua进行设置, 存储一个表,表中每一行 对应  src vocanbulary 和 dest vocanbulary

对应工具的主题逻辑代码在 replace.lua中实现,

待替换的文本文件存储在 replaceFiles文件夹下。

总体目录结果如下:

│  config.lua
│  replace.lua
│ 
└─replaceFiles
        test.txt

代码说明

代码实现路径:

https://github.com/fanqingsong/code-snippet/tree/master/lua/replace

config.lua

-- ttanslating table, in every line first word is source, second word is destination
trans_table_string = [[
    you  lucy
]]

待替换文件 test.txt

I love you

replace.lua工具逻辑代码实现

--[[
/*******************************************************************************
*  Author:
*  Date:
*  Description: set config for replace, replace by config in files of target path
*  Changes:
*******************************************************************************/
]]

local require = require
local io = io
local ipairs = ipairs
local assert = assert
local print = print
local string = string
local lfs = require"lfs"

local transFilePath = "./replaceFiles"

string.split = function(str, pat, max, regex)
    pat = pat or "\n"
    max = max or #str

local t = {}
    local c = 1

if #str == 0 then
        return {""}
    end

if #pat == 0 then
        return nil
    end

if max == 0 then
        return str
    end

repeat
        local s, e = str:find(pat, c, not regex)
        max = max - 1
        if s and max < 0 then
            t[#t+1] = str:sub(c)
        else
            t[#t+1] = str:sub(c, s and s - 1)
        end
        c = e and e + 1 or #str + 1
    until not s or max < 0

return t
end

------------------------------------------  parse start ------------------------------------------
local trans_vocabulary_table = {
    --["sourcevocabulary"] = "destvocabulary"
}

local function construct_vocabulary_table()
    require("config")
   
    print("parse trans_table starting .....")
   
    -- 禄帽募镁?拢卢 禄禄?路没  \n 潞?\r\n
    local lineSep = "\r\n"
    if string.find(trans_table_string, "\r\n") then
        lineSep = "\r\n"
    elseif string.find(trans_table_string, "\n") then
        lineSep = "\n"
    elseif string.find(trans_table_string, "\r") then
        lineSep = "\r"
    end

local lines = trans_table_string:split(lineSep)

for _,line in ipairs(lines) do
        print("line="..line)

local src, dest = string.match(line, "([%w_]+)%s+([%w_]+)")

if src then
            print("well formed line="..line)
           
            trans_vocabulary_table[src] = dest
        end
    end
 
      print("parse trans_table ending .....")
   
end

-- parse table
construct_vocabulary_table()

------------------------------------------  parse end ------------------------------------------

------------------------------------------  read file list start ------------------------------------------
local targetFiles = {}

local function infilter(file, filters)
    if filters == nil or filters == "*" then
        return true
    end

for _, v in pairs(filters) do
        if string.find(file, "%."..v.."$") then
            return true
        end
    end
   
    return false
end

local function splitonlast (path, sep)
    local dir, file = string.match(path,"^(.-)([^:/\\]*)$")
    return dir, file
end

function readdir(dir, filelist, filters)
    for file in lfs.dir(dir) do
        if file ~= ".." and file ~= "." then
            local f = dir.."/"..file
            if lfs.attributes(f).mode == "directory" then
                readdir(f, filelist, filters)
            else
                if infilter(file, filters) then
                    table.insert(filelist, f)
                end
            end
        end
    end
end

readdir(transFilePath, targetFiles, {"*"})

for _,file in ipairs(targetFiles) do
    --print("c file =".. file)
end

------------------------------------------  read file list end ------------------------------------------

------------------------------------------  handle file start ------------------------------------------

local function handle_file(file)
    local lineBuff = {}

-- ?赂?搂?
    local fh = assert(io.open (file, "rb"))
    local contents = fh:read("*a")
    fh:close()
    --print(contents)
    for src,dest in pairs(trans_vocabulary_table) do
        print(src.."==>"..dest)
        contents = string.gsub(contents, src, dest)
    end

--[[
    -- 禄帽募镁?拢卢 禄禄?路没  \n 潞?\r\n
    local lineSep = "\r\n"
    if string.find(contents, "\r\n") then
        lineSep = "\r\n"
    elseif string.find(contents, "\n") then
        lineSep = "\n"
    elseif string.find(contents, "\r") then
        lineSep = "\r"
    end

local fileLines = string.split(contents, lineSep)

for _,line in ipairs(fileLines) do
        --print(" handle_file line= "..line)
           
        local gotPattern = false
        for src,dest in pairs(trans_vocabulary_table) do
            --print("src="..src.."----")
            local s, e = string.find(line, "%s-%(%s-"..src.."%s-,%s-%\"")
            if s then
                print("!!!! ------- gotPattern ------- src ="..src)

gotPattern = true

-- the part before OssUsersrc
                local head = string.sub(line, 1, s-1)
                -- tail part = now");
                --print(head)
                local tail = string.sub(line, e+1)
                --print("tail="..tail)
                --print("tail[1]="..string.sub(tail, 1,1))

-- OssUserLogType(LOG_LEVEL_NOTICE, LOG_TYPE_SYSTEM, "the system will reboot now");
                local level = dest["level"]
                local types = dest["types"]
                local msg = dest["msg"]

local sep = " "
                if msg == "" then
                    sep = ""               
                elseif string.sub(tail, 1,1) == "\"" then
                    sep = ""
                end
                --print("msg="..msg.."sep="..sep.."--")
                local transLine = head .. "OssUserLogType(" .. level ..", " .. types .. ", \"" .. msg .. sep .. tail

table.insert(lineBuff, transLine)

if gotPattern then
                    break
                end

end
        end

if not gotPattern then
            table.insert(lineBuff, line)
        end
    end
   
]]
    --write buff to orig file
    local fh = assert(io.open(file, "wb"))
    fh:write(contents)
    fh:close()
end

for _,file in ipairs(targetFiles) do
    print("handling file =".. file)
    handle_file(file)
end

------------------------------------------  handle file end ------------------------------------------

运行结果

root@fqs:/home/share/luascript/replace# cat ./replaceFiles/test.txt

I love you

root@fqs:/home/share/luascript/replace# lua replace.lua
parse trans_table starting .....
line=    you  lucy
well formed line=    you  lucy
line=
parse trans_table ending .....
handling file =./replaceFiles/test.txt
you==>lucy
root@fqs:/home/share/luascript/replace#
root@fqs:/home/share/luascript/replace#
root@fqs:/home/share/luascript/replace# cat ./replaceFiles/test.txt

I love lucy

root@fqs:/home/share/luascript/replace#

LUA实现单词替换功能相关推荐

  1. Word中查找和替换功能详细介绍

    在Word中查找和替换功能很多人都会使用,最通常是用它来查找和替换文字,但实际上还可用查找和替换格式.段落标记.分页符和其他项目,并且还可以使用通配符和代码来扩展搜索. 一.查找和替换文字 例如:将& ...

  2. php 查找文件 替换内容,关于php:文件中查找和替换功能困扰

    我知道这不是编程问题吗? 但是我需要另一个有关在PHP代码编辑器中查找和替换功能的帮助. 我正在使用eclipse和Dreamweaver,我有大约650个php文件,并希望替换所有文件中的字符串而无 ...

  3. sql server 替换_SQL Server替换功能–全面指南

    sql server 替换 Hello, readers! In this article, we will be understanding the working of SQL Server Re ...

  4. VB应用程序中实现查找和替换功能

    一?前言 尽管Visual Basic并不是我最喜欢的开发工具,但我喜欢它简单而又丰富的库集.每当开发一个需要处理大量文本数据的应用程序时,需要具有拼写错误纠正功能,例如,微软的Word程序,当运行& ...

  5. python 读excel每行替换_Python脚本操作Excel实现批量替换功能

    Python脚本操作Excel实现批量替换功能 大家好,给大家分享下如何使用Python脚本操作Excel实现批量替换. 使用的工具 Openpyxl,一个处理excel的python库,处理exce ...

  6. 替换功能replaceAll

    /** 替换功能* String类的public String replaceAll(String regex,String replacement)* 使用给定的 replacement 替换此字符 ...

  7. 两个excel文档查找相同选项后替换_看似普通的查找和替换功能,用好了,能让你的工作效率翻一番...

    关注[新精英充电站]能力提升看得见! 在Word中,查找和替换功能是编辑文档时时常要用到的重要功能,它能帮助我们快速将文档或表格中查找到的内容或格式等替换为指定的内容或格式,特别是遇到大量需要修改的相 ...

  8. Leetcode 648.单词替换

    单词替换 在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词--我们称这个词为 继承词(successor).例如,词根an,跟随着单词 other(其他),可 ...

  9. python读取坐标文本文件_Python 实现文件读写、坐标寻址、查找替换功能

    读文件 打开文件(文件需要存在) #打开文件 f = open("data.txt","r") #设置文件对象 print(f)#文件句柄 f.close() ...

最新文章

  1. 使用C#的HttpWebRequest模拟登陆网站
  2. 冠军奖3万元!CSDN×易观算法大赛开赛啦
  3. CRM成功实施如何化繁为简
  4. Install FileZilla in Ubuntu16.04
  5. linux系统下安装配置iSCSI教程
  6. 面试:讲一讲Spring中的循环依赖
  7. 中原银行张本晨:中原银行数字化营销体系建设实践
  8. ASP.NET Core 源码学习之 Logging[3]:Logger
  9. 递归:我不用栈 非递归:栈使我快乐
  10. A*算法一个简单的记录
  11. java_js_json_日期格式化
  12. CMMI 项目监督与控制(PMC)
  13. 如何摆脱工具类【转载】
  14. ucgui移植到rt_thread simulator
  15. EmmyLua Unity断点调试
  16. gym100818F-F - Irrational Roots
  17. Matlab c2d离散用法
  18. 灰度图转热力图_热力图下看区域城市密集度,密集度较高的主要在沿海和省会周边...
  19. Laya.TextInput组件中禁用后改变输入框背景色和文字颜色
  20. 威纶通触摸屏232脚位_威纶通各系列触摸屏引脚排列.pdf

热门文章

  1. ProE常用曲线方程:Python Matplotlib 版本代码(玫瑰曲线)
  2. 如何在Kubernetes上运行Apache Flink
  3. mysql的分库分表
  4. 静态Include和动态Include测试并总结
  5. SQL SERVER 2005允许自定义聚合函数
  6. 2013长春区域赛总结
  7. 三月份总结(后台规范+面试)
  8. 7-zip来解压大于4G以上打包文件
  9. VS.NET 2003 安装问题
  10. Error while compiling statement: FAILED: LockException [Error 10280]