【发布时间】:2015-12-14 08:59:19
【问题描述】:
我正在尝试读取一个大文件并返回一个包含字数的表格。 我在lua.org 上找到了一个高效读取大文件的示例,并提出了我的小脚本的最终版本。
function cnt_word(stream)
local BUFSIZE = 2^13 -- 8KB
local sin = io.input(stream) -- open input file
local wc = {}
local text = ""
while true do
local data, line = sin:read(BUFSIZE, '*l')
if not data then break end
if line then data = data .. line .. '\n' end
text = data
end
-- creating a table with word counts
for m in text:gmatch("%w+") do
if not wc[m] then wc[m] = 0 end
wc[m] = wc[m] + 1
end
return wc
end
input, word = arg[1], arg[2]
if not input then print("Error! Provide a valid filename") os.exit() end
if not word then print("Error! Provide a valid query term") os.exit() end
cnts = cnt_word(input)
cnt = cnts[word]
if not cnt then
print(string.format("'%s' not found in '%s'", word, input))
os.exit()
end
print(string.format("'%s' cnt: %s", word, cnt))
这个脚本的问题是它只返回文件的最后约 70 行,我不知道为什么。行连接if line then data = data .. line .. '\n' end 被执行了大约 3k 次,这足以收集data 变量中的全部数据。但是,当我检查循环内data 的长度时,它并没有增长,而是在 8k 左右波动,此外,当我检查text 的长度时,由于某种原因,它大约是 3k。我不明白 Lua 对数据做了什么以及为什么这样做。有人能帮我弄清楚吗?
【问题讨论】:
标签: lua