2016-05-30 89 views
0

我有一個文件中的文本 「A.TXT」:讀取文件中的文本和存儲在陣列2D

1 2 3 
4 5 6 
7 8 9 

現在我想將它存儲在陣列2D:

陣列= {{1,2, 3} {4,5,6} {7,8,9}} 我已經嘗試:

array ={} 
file = io.open("a.txt","r") 
io.input(file) 
i=0 
for line in io.lines() do 
    array[i]=line 
    i=i+1 
end 

但它沒有成功。 有人建議我做一個方法嗎?

回答

3

您的代碼中存在一些錯誤。首先打開文件a.txt,然後將其設置爲標準輸入。你不需要open()。但我建議打開文件並在其上運行,使用lines()迭代器上的文件:

array = {} 
file = io.open("a.txt","r") 
i = 0 
for line in file:lines() do 
    array[i]=line 
    i=i+1 
end 

另外,與你的方法,你不會得到你所希望的({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} })數組,而是一個數組包含字符串作爲元素: { "1 2 3", "4 5 6", "7 8 9" }。 爲了得到後者,你必須解析你讀過的字符串。一個簡單的方法來做到這一點是使用string.match與捕獲:

array ={} 
file = io.open("a.txt","r") 
for line in file:lines() do 
    -- extract exactly three integers: 
    local t = { string.match(line, "(%d+) (%d+) (%d+)")) } 
    table.insert(array, t) -- append row 
end 

https://www.lua.org/manual/5.3/manual.html#pdf-string.match。有關每一行的整數(或其他數字)的任意數,你可以用string.gmatch()一起使用一個循環:

array ={} 
file = io.open("a.txt","r") 
for line in file:lines() do 
    local t = {} 
    for num in string.gmatch(line, "(%d+)") do 
     table.insert(t, num) 
    end 
    table.insert(array, t) 
end 
+0

這正是我期待的。非常感謝你! – ledien

+0

不客氣!如果你喜歡我的回答,善良,接受它:) – pschulz

+2

你可以使用'for line in io.lines(「a.txt」)do'。 – lhf