2011-12-15 67 views
0

考慮以下文本(CSV)文件:如何從文本(csv)文件加載二維數組到八度?

1, Some text 
2, More text 
3, Text with comma, more text 

如何將數據加載到八度的2D陣列?該號碼可以進入第一列,並且第一個逗號(包括其他逗號)右側的所有文本進入第二個文本列。

如有必要,我可以用不同的分隔符替換第一個逗號。

回答

0

經過許多長時間的搜索和調試,以下是我如何在Octave 3.2.4上工作。使用|作爲分隔符(而不是逗號)。

數據文件現在看起來像:

1|Some text 
2|More text 
3|Text with comma, more text 

以下是如何稱呼它:data = load_data('data/data_file.csv', NUMBER_OF_LINES);

限制:你需要知道你要多少線就搞定了。如果你想得到全部,那麼你需要編寫一個函數來計算文件中的行數,以便初始化cell_array。這一切都非常笨重和原始。非常適合像「八度」這樣的高級語言。

注意:經過令人不快的工作後,似乎Octave不是很有用,除非你喜歡浪費時間編寫代碼來做最簡單的事情。更好的選擇似乎是使用機器學習或矩陣庫的R,Python或C#/ Java。

function all_messages = load_data(filename, NUMBER_OF_LINES) 
    fid = fopen(filename, "r"); 

    all_messages = cell (NUMBER_OF_LINES, 2); 
    counter = 1; 

    line = fgetl(fid); 

    while line != -1 
     separator_index = index(line, '|'); 
     all_messages {counter, 1} = substr(line, 1, separator_index - 1); % Up to the separator 
     all_messages {counter, 2} = substr(line, separator_index + 1, length(line) - separator_index); % After the separator 
     counter++; 

     line = fgetl(fid); 
    endwhile 

    fprintf("Processed %i lines.\n", counter -1); 
    fclose(fid); 
end 
1

AFAIK你不能把不同大小的蜇刺放入一個數組中。您需要創建一個所謂的cell array

一種可能的方法來讀取存儲在一個文件Test.txt的成單元陣列你的問題的數據是

t1 = textread("Test.txt", "%s", "delimiter", "\n"); 
for i = 1:length(t1) 
    j = findstr(t1{i}, ",")(1); 
    T{i,1} = t1{i}(1:j - 1); 
    T{i,2} = strtrim(t1{i}(j + 1:end)); 
end 

現在
T{3,1}給你3
T{3,2}給你Text with comma, more text

+0

什麼是文本閱讀?我得到`錯誤:'textread'undefined` – 2011-12-16 01:06:11

相關問題