【问题标题】:Can I ignore comment lines while reading in a csv file in Octave/MATLAB?在 Octave/MATLAB 中读取 csv 文件时可以忽略注释行吗?
【发布时间】:2014-11-30 03:20:24
【问题描述】:

我有一个看起来像这样的数据文件:

# data file
# blah
# blah

       0.000000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.020000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.040000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.060000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.080000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.100000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN
       0.120000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN

我想用 Octave 程序来阅读它。

csvread(file,3,0) 在这种情况下完美运行,但我担心必须手动计算 3。

有什么方法可以说“在执行 csvread 之前丢弃所有以 # 开头的行和任何空白行”?

【问题讨论】:

    标签: matlab parsing csv comments octave


    【解决方案1】:

    八度音阶你可以做

    d = load("yourfile")
    

    应该忽略 # 行

    编辑: 以上使用文件类型的自动检测,您也可以使用d = load ("-ascii", "yourfile"). Quote from help load 强制它:

     '-ascii'
          Force Octave to assume the file contains columns of numbers in
          text format without any header or other information.  Data in
          the file will be loaded as a single numeric matrix with the
          name of the variable derived from the name of the file.
    

    不幸的是,帮助没有提到以 % 或 # 开头的行被忽略。为此,您必须查看源代码(幸运的是,由于 GNU Octave 是免费软件,所以可以使用)get_mat_data_input_line from octave source

    从那里您可以看到 % 或 # 之后的所有字符都被跳过。

    【讨论】:

    • 非常简单,快速,谢谢!希望我在写我的之前看到你的答案......
    • @JohnLawrenceAspden gnu.org/software/octave/doc/interpreter/…,似乎默认为“-ascii”
    • @huntj:加载命令没有默认值,但它会尝试自动检测文件类型。保存的默认值是“-text”,它也是人类可读的,但包括 var 类型、大小和其他信息。
    【解决方案2】:

    csvread 不允许此选项。相反,您可以使用textscan,但是,您需要知道您的 csv 文件有多少列(或行)。

    例如:

    fid = fopen('csvFile.csv','r');
    c = textscan(fid,'%f','commentStyle','#','delimiter',',');
    fclose(fid); %# close the file as soon as we don't need it anymore
    
    array = reshape([c{:}],[],7)';
    

    【讨论】:

      【解决方案3】:

      这是一种跳过以注释字符串开头的标题行的方法。 csvread 行可以替换为 dlmread 调用以获取除 ',' 以外的分隔符。这两个函数都比 octave 3.8.2 上的 textscan 快​​得多。

      fid = fopen('csvFile.csv','r');
      
      comment = '#';
      while strcmp(fgets(fid, length(comment)), comment)
          % line begins with a comment, skip it
          fskipl(fid);
      endwhile
      % get back, because the last read length(comment) characters
      % are not comments, actually
      fseek(fid, -length(comment), SEEK_CUR);
      
      c = csvread(fid);
      
      fclose(fid); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 2015-09-15
        • 2017-04-02
        • 2012-10-29
        • 2015-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多