如何输出多列。

我想处理像这样的数据文件:

2015-02-23  190   170   131   14  8   9   130 85  102.0   12  68
2015-02-24  165   128   97    14  7   6   110 75  101.7   12  64
2015-02-25  160   123   129   11  5   7   130 85  101.3   12  68
2015-02-26  151   115   128   11  nan 7   120 80  100.9   12  64
2015-02-27  141   119   130   11  4   nan 130 85  101.6   12  68
2015-02-28  142   137   143   nan nan nan 120 80  101.2   12  64

并输出一些列。

到目前为止,我成功了:

local infile = arg[1]
local outfile = arg[2]
local column = tonumber(arg[3])
local data = {}
local row = 0
local ofile

for line in io.lines(infile)
do
  row = row + 1
  data[row] = {}
  local i = 0
  for value in string.gmatch(line, "%S+") do
    i = i + 1
    data[row][i] = value
  end
end

ofile = assert(io.open(outfile, "w"))
for i = 1,row do
  ofile:write(data[i][column] .. "\n")
end
ofile:close()

这对于一列很好用:lua column.lua test.dat new.dat 2

190
165
160
151
141
142

我想要的是lua column.lua test.dat new.dat 1,2,4,将把第1列、第2列和第4列放入新文件。这可能吗?

点赞
用户1442917
用户1442917

下面函数可用于提取一列列表:

function cols(t, colnums, prefix)
  -- 获取第一列数字和剩下的数字
  -- 它将 1,2,3 分割成 1 和 2,3
  local col, rest = colnums:match("^(%d+)[,%s]*(.*)")
  -- 如果没有提供列数,返回当前的 `prefix` 值(可能为 `nil`)
  if not col then return prefix end
  -- 将列数字符串转换为数字
  -- 这是必需的,因为 t[1] 和 t['1'] 引用不同的值
  local val = t[tonumber(col)]
  -- 递归调用相同的函数,但使用剩余的列
  -- 这也将当前值连接到前缀(如果有的话)上
  return cols(t, rest, prefix and prefix.."\t"..val or val)
end

现在,您可以使用 ofile:write(cols(data[i], arg[3]) .. "\n") 代替 ofile:write(data[i][column] .. "\n")。由于它会对每一行进行解析,因此对于大量行可能不太高效,所以如果是这种情况,您可能需要在脚本开头将其解析一次。

2015-05-14 17:17:35