Lua - 在连字符处拆分CSV列
2017-12-29 0:47:35
收藏:0
阅读:145
评论:1
我想要使用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
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

假设每行的第二个值总是姓名,并且姓名中的第一个或唯一的连字符是名称中的第一个或唯一的连字符(不一定是安全的假设),那么您可以从输入中读取每行数据(我使用了一个字符串,但这可以是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