【问题标题】:Find and replace text file Matlab查找和替换文本文件 Matlab
【发布时间】:2014-07-05 03:05:58
【问题描述】:

我正在编写一个生成数组编号的 Matlab 代码,它应该替换文本文件中的每个数字(已经存在)并用它替换所有实例。该数字应为字符串格式。我已经做到了:

ita='"';
for i=1:size(z,2)
word_to_replace=input('Replace? ','s');
tik=input('Replacement? ','s');
coluna=input('Column? ');
files = dir('*.txt');
for i = 1:numel(files)
    if ~files(i).isdir % make sure it is not a directory
        contents = fileread(files(i).name);
        fh = fopen(files(i).name,'w'); 
        val=num2str(z(i,coluna));
        word_replacement=strcat(tik,val,ita);
        contents = regexprep(contents,'word_to_replace','word_replacement');
        fprintf(fh,contents); % write "replaced" string to file
        fclose(fh) % close out file
    end
end
end

我希望代码打开文件#1 ('file.txt'),找到所有实例 'word_replacement' 并将其替换为 'word_to_replace' 并保存到同一个文件。 txt文件个数未定义,可以是100个,也可以是10000个。

非常感谢。

【问题讨论】:

    标签: matlab file replace find


    【解决方案1】:

    您的代码的问题是以下语句:

    contents = regexprep(contents,'word_to_replace','word_replacement');
    

    您正在使用正则表达式在文本文件中查找word_to_replace 的任何实例并将它们更改为word_replacement。查看您的代码,似乎这些都是包含字符串的变量。我假设您想要变量的 contents 而不是变量的实际名称。

    因此,只需删除 regexprep 的第二个和第三个参数周围的引号就可以了。

    换句话说,这样做:

    contents = regexprep(contents, word_to_replace, word_replacement);
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 1970-01-01
      • 2013-05-26
      • 2019-07-30
      • 2019-10-16
      • 1970-01-01
      • 2011-08-20
      • 2011-11-24
      • 2021-10-25
      相关资源
      最近更新 更多