Lua-在连字符处拆分CSV列
我想使用Lua CSV 并且需要将其中一个使用连字符“-”的列(例如:First姓氏)拆分到它创建的表中。我可以在excel中使用“数据>文本到列”手动执行此操作,这将拆分全名单元格,并在末尾添加第一列和姓氏列,我需要Lua在脚本中执行相同操作:Lua-在连字符处拆分CSV列,csv,parsing,lua,lua-table,Csv,Parsing,Lua,Lua Table,我想使用Lua CSV 并且需要将其中一个使用连字符“-”的列(例如:First姓氏)拆分到它创建的表中。我可以在excel中使用“数据>文本到列”手动执行此操作,这将拆分全名单元格,并在末尾添加第一列和姓氏列,我需要Lua在脚本中执行相同操作: Before Age,Name,Start,End,Length,Score 35,Bill-Smith,2.2.2017,2.4.2017,0.2.00,2056 After Age,Name,Start,End,Length,Score,Firs
Before
Age,Name,Start,End,Length,Score
35,Bill-Smith,2.2.2017,2.4.2017,0.2.00,2056
After
Age,Name,Start,End,Length,Score,First,Surname
35,Bill-Smith,2.2.2017,2.4.2017,0.2.00,2056,Bill,Smith
这是要使用的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
假设每行的第二个值始终是名称,并且始终包含最后一个连字符分隔符作为名称中的第一个或唯一连字符(不一定是安全的假设),那么您可以从输入中读取每一行(我使用了字符串,但这可能是IO读取器或您正在使用的任何东西),使用模式将第二个值解析为名字和姓氏,将它们附加到读取行的末尾,然后将其写回(我在这里将其插入表中进行演示):
你的问题是什么?小猪说了什么。目前还不清楚你的问题是什么,CSV的中间有一个名字字符串。我需要Lua在连字符处拆分该单元格,将它们添加到表中的两个新单元格中。为什么不用图书馆?像lua csv:
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 --get next group of letters up to the next CR or LF character
local name = string.match (line, '^.-,(.-),') -- assuming that the name field is always the second value here
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