Lua - 在连字符处拆分CSV列

我想要使用Lua CSV http://lua-users.org/wiki/LuaCsv,并且需要将其中一个使用连字符"-"的列拆分成创建的表格。我可以在Excel中使用数据 > 文本到列功能手动拆分全名单元格,并在末尾添加名字和姓氏列,我需要Lua在脚本中执行相同的操作:

之前
年龄,姓名,开始,结束,长度,分数
35, 比尔 - 史密斯,2.2.2017,2.4.2017,0.2.00,2056

之后
年龄,姓名,开始,结束,长度,分数,名字,姓氏
35, 比尔 - 史密斯,2.2.2017,2.4.2017,0.2.00,2056,比尔,史密斯

这是要使用的Lua csv解析器:

function ParseCSVLine (line,sep)
    local res = {}
    local pos = 1
    sep = sep or ','
    while true do
        local c = string.sub(line,pos,pos)
        if (c == "") then break end
        if (c == '"') then
            -- quoted value (ignore separator within)
            local txt = ""
            repeat
                local startp,endp = string.find(line,'^%b""',pos)
                txt = txt..string.sub(line,startp+1,endp-1)
                pos = endp + 1
                c = string.sub(line,pos,pos)
                if (c == '"') then txt = txt..'"' end
                -- check first char AFTER quoted string, if it is another
                -- quoted string without separator, then append it
                -- this is the way to "escape" the quote char in a quote. example:
                --   value1,"blub""blip""boing",value3  will result in blub"blip"boing  for the middle
            until (c ~= '"')
            table.insert(res,txt)
            assert(c == sep or c == "")
            pos = pos + 1
        else
            -- no quotes used, just look for the first separator
            local startp,endp = string.find(line,sep,pos)
            if (startp) then
                table.insert(res,string.sub(line,pos,startp-1))
                pos = endp + 1
            else
                -- no separator found -> use rest of string and terminate
                table.insert(res,string.sub(line,pos))
                break
            end
        end
    end
    return res
end
点赞
用户736889
用户736889

假设每行的第二个值总是姓名,并且姓名中的第一个或唯一的连字符是名称中的第一个或唯一的连字符(不一定是安全的假设),那么您可以从输入中读取每行数据(我使用了一个字符串,但这可以是IO reader或您正在使用的任何东西),使用模式将第二个值解析为名字的第一个和最后一个字母,将它们附加到读取的行的末尾,然后将其写回(我在这里将其插入到一个表中进行演示):

local input = [[
35,Bill-Smith,2.2.2017,2.4.2017,0.2.00,2056
31,Ben-Smith,2.4.2015,2.6.2012,0.2.01,2058
32,Bob-Smith,2.3.2016,2.7.2011,0.2.02,2057
]]

local output = {}

for line in string.gmatch (input, '[^\010\014]+') do --获取下一行中的字母组,直到下一个CR或LF字符
    local name = string.match (line, '^.-,(.-),') --假设这里的名字字段总是第二个值
    local first, last = string.match (name or '', '^(.-)%-(.+)$')
    line = line .. ',' .. (first or '') .. ',' .. (last or name or '')
    table.insert (output, line)
end

print (table.concat (output, '\r\n'))

>>>>>>>
35,Bill-Smith,2.2.2017,2.4.2017,0.2.00,2056,Bill,Smith
31,Ben-Smith,2.4.2015,2.6.2012,0.2.01,2058,Ben,Smith
32,Bob-Smith,2.3.2016,2.7.2011,0.2.02,2057,Bob,Smith
2018-01-31 21:40:10