【发布时间】:2011-12-15 01:02:44
【问题描述】:
考虑以下文本(csv)文件:
1, Some text
2, More text
3, Text with comma, more text
如何在 Octave 中将数据加载到二维数组中?数字可以进入第一列,第一个逗号右侧的所有文本(包括其他逗号)进入第二个文本列。
如有必要,我可以将第一个逗号替换为不同的分隔符。
【问题讨论】:
标签: file-io csv octave text-files
考虑以下文本(csv)文件:
1, Some text
2, More text
3, Text with comma, more text
如何在 Octave 中将数据加载到二维数组中?数字可以进入第一列,第一个逗号右侧的所有文本(包括其他逗号)进入第二个文本列。
如有必要,我可以将第一个逗号替换为不同的分隔符。
【问题讨论】:
标签: file-io csv octave text-files
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。
经过大量长时间的搜索和调试,下面是我如何让它在 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);
限制:您需要知道要获得多少行。如果你想得到all,那么你需要编写一个函数来计算文件中的行数以初始化cell_array。这一切都非常笨重和原始。 “像 Octave 这样的高级语言”就这么多。
注意:经过不愉快的练习之后,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
【讨论】: