0

I'm reasonably new to Lua although I have used other languages which are similar. So far I've spent 8 hours to no avail trying to parse a large text file.

The file in question looks something like this: (but thousands of lines long)

A|KLAX|LOS ANGELES INTERNATIONAL|33942522|-118407161|125

I've got the user to enter the KLAX variable, but my goal is to get out this part of the line in question WITHOUT using tables: 33942522|-118407161

E.g.

APTDEP_DATA = 33942522|-118407161

Or even get a whole line out of the .txt file as a string?

E.g.

APTDEP_DATA = A|KLAX|LOS ANGELES INTERNATIONAL|33942522|-118407161|125

Thanks a heap in advance. After 8 hours, it would be great to know whether what I'm trying to do is even possible. (Every tutorial I see is parsing data into tables)

I've tried a lot of things to this effect:

THE NZAA is also a code I was trying to find. So don't get confused with KLAX thing. I was just trying to get a result.

(I couldn't get the code to show properly, sorry about the link)

4

2 回答 2

4

通过查看您的示例代码段,问题来自您的使用:

AP_LAT = string.match(file, "A|NZAA")

模式匹配是在字符串值上执行的,而不是file句柄。更合适的是:

AP_LAT = string.match(line, "A|NZAA")

以下内容一次处理您的输入文件,并将其解析为相应的字段:

file = assert(io.open("Airports.txt", "r"))

for line in file:lines() do
  local fields = { line:match "(%w+)|(%w+)|([%w ]+)|([%d-]+)|([%d-]+)|([%d-]+)" }
  -- do something useful with it
  print(fields[4], fields[5])  -- the 2 numeric fields you're interested in
end

file:close()

如果您坚持没有表格,您可以将匹配项放入变量中,如下所示:

local first, second, third, etc = line:match "(%w+)|(%w+)|([%w ]+)|([%d-]+)|([%d-]+)|([%d-]+)"

注意:随意修改/优化模式以满足您的需求。这只是一个例子来说明这个想法。

于 2013-07-23T07:11:24.620 回答
0

要从文件中读取行,请使用io.lines

for line in io.lines(filename) do 
    --do some processing
end

要从行中获取特定部分,请使用模式匹配。我不确定你想从这个问题中得到什么。

于 2013-07-23T06:06:28.770 回答