为什么在lua中读取文本文件只返回最后一块内容?

我试图读取一个大文件并返回一个带有单词计数的表格。

我在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("错误!提供有效的文件名") os.exit() end
if not word then print("错误!提供有效的查询词") os.exit() end
cnts = cnt_word(input)
cnt = cnts[word]
if not cnt then
  print(string.format("'%s'没在 '%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在做什么以及为什么做这件事。 有人能帮我搞清楚吗?

点赞
用户3586583
用户3586583

你应该将进行单词计数的代码移动到 while 循环调用 text = data 之后。

代码的整体流程是读取以 BUFSIZE 大小为块的文件,然后处理该块,接着被下一块替换。 由于你的所有工作都是在读取完成后完成,所以你的单词计数函数仅处理它读取的最后一个块,而不是所有块。

2015-12-14 00:58:49
用户734069
用户734069

思考你的代码在做什么。

local data, line = sin:read(BUFSIZE, '*l')

你读取了X个字节的数据,然后读取了下一个换行符。

if not data then break end

如果没有读取到任何数据,就退出循环。

if line then data = data .. line .. '\n' end

如果 line 包含数据,那么将其连接到总数据中。

text = data

所以...你认为这段代码是做什么的?我知道它 不会 做什么。它不会将数据块与已经加载的内容 连接 起来。它会 替换 那个变量里的任何已有内容。

这意味着 text 存储的最后一个东西就是你加载的最后一个数据块。


关于效率的问题。

Lua.org上关于高效加载大型文件的说明是正确的。但是那份代码是 假设 你要加载一个块,然后 处理 那个块,然后再加载另外一个块。

你正在做的是逐块加载文件,然后将它们连接起来(好吧,你实际上 没有 这样做,但那是你想要的;),然后处理整个文件。

这是 高效的。如果你想要加载整个文件,然后将其全部加载到内存中进行处理,那么就应该使用 read("*a")

2015-12-14 00:59:19