转换lua文件中的数据格式

时间:2017-05-06 02:11:28

标签: lua string-formatting

您好我需要将720个数据集从1个内容转换为以下格式。 Atm我把它们放在一个开放的办公室文件中,每个数字都在一列中,但我不知道如何转换格式。

[12] = {
    [1] = "test2",
    [2] = "-8906.071289",
    [3] = "560.890564",
    [4] = "93.236107",
    [5] = "0",
},
[13] = {
    [1] = "Southshore",
    [2] = "-846.814636",
    [3] = "-526.218323",
    [4] = "10.981694",
    [5] = "0",
},

if

2 个答案:

答案 0 :(得分:3)

Lua的一种可能性。使用program.lua datafile运行 其中program.lua是您为此文件指定的名称,datafile是您的外部数据文件。只用program.lua

进行测试
--[[
12  -8906.071289 560.890564 93.236107 0 test2
13  -846.814636 -526.218323 10.981694 0 southshore
--]]

local filename = arg[1] or arg[0]       --data from 1st command line argument or this file
local index,head,tail

print '{'
for line in io.lines(filename) do
  if line:match '^%d+' then
    head, line, tail = line:match '^(%d+)%s+(.-)(%S+)$'
    print('  [' .. head .. '] = {\n    [1] = "' .. tail .. '",')
    index = 1
    for line in line:gmatch '%S+' do
      index = index + 1
      print('    [' .. index .. '] = "' .. line .. '",')
    end
    print '  },'
  end
end
print '}'

答案 1 :(得分:0)

这个awk程序可以做到:

{
    print "[" $1 "] = {"
    print "\t[" 1 "] = \"" $NF "\","
    for (i=2; i<NF; i++) {
        print "\t[" i "] = \"" $i "\","
    }
    print "},"
}