【问题标题】:how can I read multiple text files in matlab?matlab如何读取多个文本文件?
【发布时间】:2014-05-31 00:49:21
【问题描述】:

如果可能,请告诉我如何在 Matlab 中读取不同的文本文件。 考虑到每个人都应该处理 33 个 txt 文件。 这是我的代码有错误。 :(

 textFilename = cell(1,33);
        id = cell(1,33);
        for k=1:33;
        textFilename{k} = fullfile('C:\Users\Desktop\SentimentCode\textfiles',['file' num2str(k)     '.txt']);
        id{k} = fopen(textFilename{k},'rt'); 
        str{k} = textscan(id{k},'%s%s'); 

    end                                                      
    str(str == '.') = '';
    str(str == '_') = '';
    str(str == '-') = '';


% Remove numbers from text
    T =regexprep(str, '[\d]', ' ');                                  

  and my error is :   ??? Undefined function or method 'eq' for input arguments of type 'cell'.

Error in ==> Untitled9 at 23
str(str == '.') = '';

【问题讨论】:

  • 你得到什么错误?
  • 非常感谢您的回复.. 我编辑了我的帖子并添加了更多内容和错误感谢您的回答
  • 我在代码末尾使用了 fclose(id{k}) 。
  • 并且错误的解释也是:指示的变量或数组的大小似乎随着每次循环迭代而变化。

标签: matlab list file-io text-files textscan


【解决方案1】:

在您当前的编辑中,您的错误似乎更倾向于删除 . - 和 _ 字符。 == 比较适用于字符串,而 textscan 返回一个单元格

代替

str(str == '.') = '';
str(str == '_') = '';
str(str == '-') = '';

尝试使用

regexprep(str,'(\.|-|_)','')

一次全部替换(需要'\.',因为'.'是一个特殊字符)。 这适用于 cellstrings,因此根据您的单元格结构的深度,您可能需要在 for 循环中调用它,str{k},str{k}{1},str{k}{i } ETC... 另一种方法是查看cellfun 或/和strjoin... 取决于您的数据在文件中的排列方式。

【讨论】:

    【解决方案2】:

    只看示例代码:

    extFilename{k} = fullfile(..); 
    

    应该是

    textFilename{k} = fullfile(...);
    

    在阅读完文件后关闭文件也是个好主意:fclose(id{k})

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 2013-05-30
      相关资源
      最近更新 更多