【问题标题】:Import file into MATLAB cell array with space delimiter使用空格分隔符将文件导入 MATLAB 元胞数组
【发布时间】:2018-01-05 04:21:58
【问题描述】:

我有一个 .asc 文件“test.asc”,它由不同长度和内容的行组成。

  my name is blalala
  This is my home and I live in here
  12 13 10 is he
  he is my brother 12 13 14

如何将文件的内容导入 MATLAB 元胞数组,其中每一行都是由空格分隔符分隔的行?

  resultCellarray={
    'my'   'name' 'is'  'blalala' []    []   []     []   []
    'This' 'is'   'my'  'home'    'and' 'I' 'live' 'in' 'here'
    '12'   '13'   '10'  'is'      'he'  []   []     []   []
    'he'   'is'   'my'  'brother' '12' '13'  '14'   []   []
    }

我尝试将每一行作为一个单元格插入:

   content = textread('test.asc','%s','delimiter','\n','whitespace','');     

然后将单元格分成几列,使用: separating cell array into several columns MATLAB,但是文件很大时会花费很多时间。最快的方法是什么?

【问题讨论】:

    标签: matlab cell-array textreader


    【解决方案1】:

    这段代码应该运行得非常快(在 0.2 秒内拆分 1M 个字符):

    %generate random file
    % w=[10,13,32*ones(1,10),97:122,97:122];
    % FILE_LENGTH=10*1000*1000;mytext=char(w(randi(length(w),1,FILE_LENGTH))); 
    % fileID = fopen('z:\mytest.asc','w');fprintf(fileID,'%s',mytext);fclose(fileID);
    clear
    tic
    %settings
    Filename='z:\test.asc';
    LineDelimiter=newline;%=char(10)
    WordDelimiter=' ';
    
    %read file
    fid=fopen(Filename,'r');
    text=fread(fid,'*char')';
    fclose(fid);
    
    %fix text
    text(text==char(9))=WordDelimiter; %replace tab with space
    text(text==char(13))=[];%remove '\r'
    if text(end)~=LineDelimiter, text(end+1)=LineDelimiter;end %add eol if needed
    IdxWords=find(text==WordDelimiter);
    text(IdxWords(diff(IdxWords)==1))=[];% remove 2 spaces or more
    
    %count words per line
    IdxNewline=find(text==LineDelimiter);
    NumOfLines=length(IdxNewline); %2eol=2lines
    WordsPerLine=zeros(1,NumOfLines); %
    IdxWords=find(text==WordDelimiter|text==LineDelimiter);
    iword=1; iword_max=length(IdxWords);
    for i=1:NumOfLines
        while iword<=iword_max && IdxWords(iword)<=IdxNewline(i)
            WordsPerLine(i)=WordsPerLine(i)+1;
            iword=iword+1;
        end
    end
    MaxWords=max(WordsPerLine);
    LongestWord=max(diff(IdxWords));
    
    %split
    Output=cell(NumOfLines,MaxWords);
    pos=1;iword=0;
    for i=1:NumOfLines
        idxline=IdxNewline(i);
        for j=1:WordsPerLine(i)
            iword=iword+1;
            Output{i,j}=text(pos:IdxWords(iword)-1);
            pos=IdxWords(iword)+1;
        end
    end
    toc
    
    % disp(Output)
    

    【讨论】:

    • 这也需要很多时间。测试文件包含大约 1016000 行
    • 很多时间?多少钱?文件总大小是多少?
    • 更改为自定义拆分,速度提高 40%。您不能期望拆分为 2d 单元格的性能是 2d 双数组。为每个单元完成单独的内存分配。这段代码接近你可以在 matlab 代码中得到的最快的解决这个问题的代码。
    • 感谢您的帮助。在某些情况下,两个单词之间有不止一个空格,有时还有一个空格。因此,在某些情况下,它节省了空单元格中的空间,我只想保留单词。这种情况可以处理吗??? @Mendi Barel
    • 我在“修复文本”阶段添加了一些删除连续空格的代码(修复会降低性能),这应该可以解决您的问题。
    猜你喜欢
    • 2015-12-03
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    相关资源
    最近更新 更多