如何从text(csv)文件将2D数组加载到Octave中? [英] How to load 2D array from a text(csv) file into Octave?

查看:260
本文介绍了如何从text(csv)文件将2D数组加载到Octave中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下文本(csv)文件:

Consider the following text(csv) file:

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

如何在Octave中将数据加载到2D数组中?该数字可以进入第一列,第一个逗号右边的所有文本(包括其他逗号)都进入第二个文本列.

How to load the data into a 2D array in Octave? The number can go into the first column, and all text to the right of the first comma (including other commas) goes into the second text column.

如有必要,我可以用不同的定界符替换第一个逗号.

If necessary, I can replace the first comma with a different delimiter character.

推荐答案

经过长时间的搜索和调试,下面介绍了如何在Octave 3.2.4上运行它.使用|作为分隔符(而不是逗号).

After many long hours of searching and debugging, here's how I got it to work on Octave 3.2.4. Using | as the delimiter (instead of comma).

数据文件现在看起来像:

The data file now looks like:

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)"来说,就这么多.

Limitation: You need to know how many lines you want to get. If you want to get all, then you will need to write a function to count the number of lines in the file in order to initialize the cell_array. It's all very clunky and primitive. So much for "high level languages like Octave".

注意:经过使人不愉快的工作之后,看来Octave并不是很有用,除非您喜欢浪费时间编写代码来完成最简单的事情.带有机器学习或矩阵库的R,Python或C#/Java似乎是更好的选择.

Note: After the unpleasant exercise of getting this to work, it seems that Octave is not very useful unless you enjoy wasting your time writing code to do the simplest things. Better choices seems to be R, Python, or C#/Java with a Machine Learning or Matrix library.

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

这篇关于如何从text(csv)文件将2D数组加载到Octave中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆