2017-04-23 209 views
1

我有一個大型的750,000行文本文件,每隔幾秒會不斷更新,我希望能夠實時監控行數。我能夠做到這一點,但花費很高的響應時間。如何有效讀取大文本文件中的行數

function GetFileSize(filename) 
    local fp = io.open(filename) 
    if fp == nil then 
    return nil 
    end 
    file = {} 
    for line in fp:lines() do 
    if (file[line] ~= line) then 
     table.insert(file, line) 
    end 
    end 
    d(table.size(file)) 
    local filesize = fp:seek("end") 
    fp:close() 
    return filesize 
end 

我想要得到兩件事情,大小(字節)和行數。

但是,反覆填充750,000行的文件,不斷地從上到下讀取文件會導致相當多的處理時間。

有沒有辦法以字節爲單位獲得文件大小,但也可以獲得行數,而不會嚴重阻礙我的系統。

非常多我猜我必須在函數之外創建一個永久表,在該函數中讀取文件並將行添加到表中。但是,我不知道如何阻止它每隔幾秒就重複一次。

我是否應該放棄行計數並堅持字節返回,因爲這並不會減慢我的速度?或者是否有一種有效的方式來獲得兩者。

謝謝!

+0

如果您需要行數,而不是行的實際內容,則不需要將它們存儲在表中。只需數一數。 – tonypdmtr

+0

你在文件中存儲什麼?每條線總是長度相同嗎?你想成爲多少準確?如果適用,total_byte_count/byte_count_per_line將爲您提供行數。 – warspyking

+0

@warspyking我不需要文件中的信息,只需要處理時間最少的行數。 – kalimin

回答

1

嘗試立即閱讀整個文件並使用gsub來計算行數。你必須測試這對你來說是否足夠快。

t = f:read("*a") 
_,n = t:gsub("\n","") 
+0

我認爲這需要爲文件內容分配2個緩衝區。可以使用't:gsub(「\ n」,「\ n」)'?可能是它不會分配新的內存。 – moteus

0

以字節爲單位使用Lua Filesystem獲取文件大小。對於您可能想要使用迭代器的行數。爲了更好地實現後者,請參閱»Lua中的編程«中描述的a trick

local file = arg[0] -- just use the source file for demo 

-- Get the file size 
local lfs = assert(require"lfs") 
local attr = lfs.attributes(file) 
print(attr.size) 

-- Get number of lines 
local count = 0 
for line in io.lines(file) do 
    count = count + 1 
end 
print(count) 
1

我可以建議這個解決方案。哪些不需要讀取所有大文件。

local function char_count(str, ch) 
    local n, p = 0 
    while true do 
    p = string.find(str, ch, p, true) 
    if not p then break end 
    n, p = n + 1, p + 1 
    end 
    return n 
end 

local function file_info(name, chunk_size) 
    chunk_size = chunk_size or 4096 
    local f, err, no = io.open(name, 'rb') 
    if not f then return nil, err, no end 
    local lines, size = 0, 0 
    while true do 
    local chunk = f:read(chunk_size) 
    if not chunk then break end 
    lines = lines + char_count(chunk, '\n') 
    size = size + #chunk 
    end 
    f:close() 
    return size, lines 
end 

但如果你只需要監控一個文件,並在可以只使用任何文件監控解決方案計算行。我使用一個based on LibUV