当前位置 : 主页 > 网络编程 > lua >

解析 – 将CSV文件转换为Lua中已定义键的表

来源:互联网 收集:自由互联 发布时间:2021-06-23
我正在学习Lua为飞行模拟器构建脚本. 我有一个CSV文件,如下所示: Poti city, Poti,red,-295731.42857144,617222.85714285 Lanchhuti city, Poti,red,-299217.14285715,647851.42857142 Ozurgeti city, Poti,red,-317217.14285715,
我正在学习Lua为飞行模拟器构建脚本.

我有一个CSV文件,如下所示:

Poti city, Poti,red,-295731.42857144,617222.85714285  
Lanchhuti city, Poti,red,-299217.14285715,647851.42857142  
Ozurgeti city, Poti,red,-317217.14285715,648422.85714285  
Samtredia city, Poti,red,-287502.85714287,672022.85714285  
Abasha city, Poti,red,-284245.71428573,661108.57142857

每行包含5个字段(城市,地区,联盟,坐标-x和坐标-y在模拟器坐标参考系统中).

我需要将此文件作为lua表读取,如下所示:

citylist = {
           [1]
           {
              ["city"] = "Poti city",
              ["region"] = "Poti",
              ["coalition"] = "red",
              ["coordinate-x"] = -295731.42857144,
              ["coordinate-y"] = 617222.85714285,
           },
           [2]
           { ....... etcetc

}

我还必须为一些不同的csv文件执行此操作,并且我试图从luawiki查看一些CSV函数,但老实说我不太了解.
您能否写下一个代码示例,该代码应该按预期解析CSV文件?

PS:csv文件中从不存在任何“”字符.

编辑添加

好吧,答案1的代码似乎工作,但似乎没有像上面那样构建一个表.作为一个新手,我会尽我所能解释.

我试着解析这个文字:

123,Poty city,Poti,red,-295731.42857144,617222.85714285
124,Lanchhuti city,Poti,red,-299217.14285715,647851.42857142
125,Ozurgeti city,Poti,red,-317217.14285715,648422.85714285
126,Samtredia city,Poti,red,-287502.85714287,672022.85714285

使用此代码:

do  
    local OLo = io.open(lfs.writedir() .. "Logs/" .. "Objectivelist.txt", "r")
    local Objectivelist = {}
    for line in io.lines(OLo) do
        local objID, objName, objRegion, objCoalition, objCoordx, objCoordy = line:match("%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-)")
        Objectivelist[#Objectivelist + 1] = { ["objID"] = objID, ["objName"] = objName, ["objRegion"] = objRegion, ["objCoalition"] = objCoalition, ["objCoordx"] = objCoordx, ["objCoordy"] = objCoordy }
    end
end

然后尝试使用以下代码重建一个用于调试的差分输出:

do
    local fName = "DGWS-DEBUG-objectivelist.doc"
    local f = io.open(lfs.writedir() .. "Logs/" .. fName, "w")
    local debugOBJ = ""

    for ind, objData in pairs(Objectivelist) do
        debugOBJ = debugOBJ.. objData.objID .. "," .. objData.objName .. "," .. objData.objRegion .. "," .. objData.objCoalition .. "," .. objData.objCoordx .. "," .. objData.objCoordy .. "\n"
    end

    f:write(debugOBJ)

end

好吧,它在“for ind,objData in pairs(Objectivelist)do”行中给出了错误,说是期望一个表并且得到了nil.

我不明白错误在哪里:(,你能帮助我吗?

谢谢 :)

PS:我不知道匹配代码,但是我会尝试学习如何在目标代码工作时对值进行更严格的检查:)

您可以自己拆分CSV文件.读取文件并使用模式匹配来获取每个字段,然后将字段存储到表中.

local citylist = {}
for line in io.lines("citys.csv") do
    local city, region, coalition, coordinate_x, coordinate_y = line:match("%s*(.-),%s*(.-),%s*(.-),%s*(.-),%s*(.-)")
    citylist[#citylist + 1] = { city = city, region = region, coalition = coalition, coordinate_x = coordinate_x, coordinate_y = coordinate_y }
end

在实际代码中,您可以使用更严格的模式.例如,检查坐标的值是否真的是数字.

网友评论