【问题标题】:Convert a .csv file into a 2D table in Lua在 Lua 中将 .csv 文件转换为 2D 表
【发布时间】:2021-02-19 05:08:56
【问题描述】:

正如标题所示,我想知道如何将 Lua 中的 .csv 文件转换为 2D 表格。

例如,假设我有一个如下所示的 .csv 文件:

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0
0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0
0,0,-1,-1,-1,-1,-1,-1,0,0,0,0,-1,-1,-1,-1,-1,-1,0,0
0,0,0,-1,-1,-1,-1,0,0,0,0,0,0,-1,-1,-1,-1,0,0,0
0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

我如何将它转换成这样的东西?

local example_table = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,0,0,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0},
{0,0,-1,-1,-1,-1,-1,-1,0,0,0,0,-1,-1,-1,-1,-1,-1,0,0},
{0,0,0,-1,-1,-1,-1,0,0,0,0,0,0,-1,-1,-1,-1,0,0,0},
{0,0,0,0,-1,-1,0,0,0,0,0,0,0,0,-1,-1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}

我们将不胜感激。

【问题讨论】:

  • 用"},\n{"替换每个换行符

标签: lua lua-table


【解决方案1】:

1。不要低估 CSV。

如果您需要它的通用性,请获取适当的 CSV 解析库。如果您自己进行解析,您将错过许多可能发生的特殊情况,因此它仅适用于您了解数据并在出现问题时注意到的情况。

2。更改文件

如果您想要等效的 Lua 代码 作为输出,假设您在 Lua 中进行解析,您可以执行以下操作:

local input = get_input_somehow() -- probably using io.open, etc.

local output =
"local example_table = {\n"
..
input:gmatch("[^\n]*", function(line)
   return "{" .. line .. "};"
end)
..
"\n}"

save_output_somehow(output) -- Probably just write to a new file

3。将 CSV 解析成表格

如果你想将 CSV 文件直接读入 Lua 表,你可以这样做:

local input = get_input_somehow() -- probably using io.open, etc.

local output = {}
input:gmatch("[^\n]", function(line)
   local row = {}
   table.insert(output, row)
   line:gmatch("[^,]", function(item)
      table.insert(row, tonumber(item))
   end)
end)

do_something_with(output) -- Whatever you need your data for

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2018-07-11
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 2016-07-22
    • 2017-11-30
    • 2013-06-21
    • 1970-01-01
    相关资源
    最近更新 更多