【问题标题】:How to load 2D array from a text(csv) file into Octave?如何将文本(csv)文件中的二维数组加载到 Octave 中?
【发布时间】: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


    【解决方案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

    【讨论】:

    • 好的,我得到了 textread 的工作。我认为不支持分隔符:Currently implemented PROP arguments are: * "headerlines": VALUE represents the number of header lines to skip.
    • 根据textread 文档,上面的脚本应该是正确的,并且也应该支持分隔符,如strread 中所记录的那样(由textread 调用)。
    • @BSeven 也许你有一个旧版本的八度?我正在运行 3.4.0 版本,上面的代码在我的机器上运行。
    【解决方案2】:

    经过大量长时间的搜索和调试,下面是我如何让它在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 2017-03-10
      相关资源
      最近更新 更多