使用Lua解析txt文件并输出表格

我刚接触Lua,需要一些帮助来解析文本文件并将数据输出成表格格式。

文本文件的每一列表示GroupID IndividualID Name Status,包含以下内容:

100 1 AAA 1
100 2 BBB 2
100 3 CCC 0
200 4 DDD 1
200 5 EEE 1

我的输出希望是:

100 2
200 2

第二列是非零状态的总计数。这是我目前的代码:

function readText("sample.txt")
     local file = io.open("sample.text", "r")
          if file then
          for line in file:lines() do
               local group, individual, name, status = line:split(" ")
                    local count = 0
                    if status ~= "0" then count = count + 1
                            table.insert (group, count)
                    print (group, count)
     end
     file:close()
 else
 end
end

为了输出第二个GroupID的计数,我是否需要使用:

if group ~= group then
table.insert (group, count)

提前感谢您的帮助!

点赞
用户107090
用户107090

尝试使用内部循环:

local last=nil
local count=0
for line in ifile:lines() do
    local group,status=line:match("^(%S+)%s.*%s(%S+)$")
    if group~=last then
        if count>0 then
            print(last,count)
        end
        count=0
        last=group
    end
    if status~="0" then
        count=count+1
    end
end
if count>0 then
    print(last,count)
end
2013-11-02 17:25:01