【问题标题】:Using Lua to parse a txt file and output a table使用Lua解析txt文件并输出表格
【发布时间】:2013-11-03 02:57:15
【问题描述】:

我是 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)

提前感谢您的帮助!

【问题讨论】:

    标签: parsing lua


    【解决方案1】:

    试试这个内循环:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      • 2020-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多