LUA implements word substitution functionality

Source: Internet
Author: User

Background description

Programming or document processing, often encountered the need to change one word to another word, for example, named shall modified to should.

The use of tools to achieve, it is more convenient, not prone to error, free hands.

Requirements Specification

For all text files (TXT) in a folder, replace a word with the target word.

Implementation ideas

For alternate word mappings, set up in configuration file Config.lua, store a table with each row in the table corresponding to the SRC vocanbulary and dest vocanbulary

The subject logic code of the corresponding tool is implemented in Replace.lua,

The text file you want to replace is stored under the Replacefiles folder.

The overall catalog results are as follows:

│config.lua
│replace.lua

└─replacefiles
Test.txt

Code description

Code implementation Path:

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

Config.lua

--ttanslating table, in every line first word was source, second word is destination
trans_table_string = [[
You Lucy
]]

File to be replaced Test.txt


I Love You

Replace.lua Tool Logic Code implementation

--[[
/*******************************************************************************
* 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 .....")

--Lu hat raises the magnesium Luro Lu Road not a LU? \ 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) does
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

------------------------------------------the Read file list end------------------------------------------


------------------------------------------Handle file Start------------------------------------------

Local function handle_file (file)
Local Linebuff = {}

--? bribery?
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

--[[
--Lu hat raises the magnesium Luro Lu Road not a LU? \ 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, +))

--Ossuserlogtype (Log_level_notice, Log_type_system, "The SYSTEM would reboot now");
Local level = dest["level"]
Local types = dest["Types"]
Local msg = dest["MSG"]

Local Sep = ""
If msg = = "" Then
Sep = ""
ElseIf string.sub (tail) = = "\" "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------------------------------------------

Run results

[Email protected]:/home/share/luascript/replace# cat./replacefiles/test.txt

I Love You


[Email protected]:/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
[Email protected]:/home/share/luascript/replace#
[Email protected]:/home/share/luascript/replace#
[Email protected]:/home/share/luascript/replace# cat./replacefiles/test.txt

I Love Lucy


[Email protected]:/home/share/luascript/replace#

LUA implements word substitution functionality

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.