【问题标题】:Matlab - Read csv file with complex stringsMatlab - 读取具有复杂字符串的 csv 文件
【发布时间】:2013-10-31 19:02:11
【问题描述】:

我有一个 csv 文件,其中包含以下行:

"some text", "more text hello 392 392", "etc complicated string here with spaces and commas"

如何将这个文件作为一个大矩阵读取?

【问题讨论】:

  • 你真的要["some text", "more text hello 392 392", "etc complicated string here with spaces and commas"]吗?这是一个 1x82 字符数组。可能您正在寻找 1x3 单元? {"some text", "more text hello 392 392", "etc complicated string here with spaces and commas"}
  • 是的,没错——对不起
  • 为了更容易...我只是想把它作为一个 bix 矩阵读入
  • @DangKhoa 看起来不像是复制品。是的,这两个问题都讨论了 CSV 文件,但它们的格式非常不同。

标签: matlab csv


【解决方案1】:

在我看来,最明智的做法是使用正则表达式来匹配正确的模式(引号和逗号对):

%// Read lines as strings
fid = fopen('input.txt', 'r');
C = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);

%// Tokenize each line using a regular expression
C = cellfun(@(x){[x{:}]}, regexp(C{:}, '"([^"]*)"(?:\s*,\s*)?', 'tokens'));

生成的元胞数组C 应包含所有所需的逗号分隔值作为标记。

示例

假设您的文件名为“input.csv”,并包含以下内容:

"some text", "more text hello 392 392", "string spaces and commas ,,,"
"hello, world!"

之后:

fid = fopen('input.csv', 'r');
C = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
C = cellfun(@(x){[x{:}]}, regexp(C{:}, '"([^"]*)"(?:\s*,\s*)?', 'tokens'));

结果应该是:

C(1, 1) =
    'some text'
    'more text hello 392 392'
    'string spaces and commas ,,,'

C(1, 2) = 
    'hello, world!'

【讨论】:

    【解决方案2】:

    所以你要求的是简单的文字阅读?

    fid=fopen('dummy.csv');
    a=[];
    while(1) ;
        tline = fgetl(fid);
        if ~ischar(tline)
            break;
        end
        a=[a;char(tline)];
    end
    fclose(fid);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多