在txt中将wordA替换为wordB,然后将其保存在新文件中。MATLAB

在txt中将wordA替换为wordB,然后将其保存在新文件中。MATLAB,matlab,file-io,Matlab,File Io,我如何编写函数来接受以下内容: 文件名:(与文件名相对应的字符串) wordA和wordB:它们都是没有空格的两个字符串 该函数应执行以下操作: A-逐行读取A txt文件 B-将每次出现的wordA替换为wordB。 C-使用与原始文件相同的格式编写修改后的文本文件,但以“new_”开头。例如,如果输入文件名为'data.txt',则输出为'new_data.txt' 这就是我所做的。它有这么多的错误,但我得到了主要的想法。你能帮我找出我的错误并使功能正常工作吗 function [ ] =

我如何编写函数来接受以下内容: 文件名:(与文件名相对应的字符串) wordA和wordB:它们都是没有空格的两个字符串

该函数应执行以下操作: A-逐行读取A txt文件 B-将每次出现的wordA替换为wordB。 C-使用与原始文件相同的格式编写修改后的文本文件,但以“new_”开头。例如,如果输入文件名为'data.txt',则输出为'new_data.txt'

这就是我所做的。它有这么多的错误,但我得到了主要的想法。你能帮我找出我的错误并使功能正常工作吗

function [ ] = replaceStr( filename,wordA, wordB )
% to replace wordA to wordB in a txt and then save it in a new file.

newfile=['new_',filename]
fh=fopen(filename, 'r')
fh1=fgets(fh)
fh2=fopen(newfile,'w')
line=''
while ischar(line)
    line=fgetl(fh)
    newLine=[]
while ~isempty(line)
    [word line]= strtok(line, ' ')
if strcmp(wordA,wordB)
word=wordB
      end
newLine=[ newLine word '']
end
newLine=[]
fprintf('fh2,newLine')
end

fclose(fh)
fclose(fh2)

end
需要解决的一些问题:

  • 使用该函数比自己解析文本要容易得多
  • 我将使用而不是保留换行符作为字符串的一部分,因为您无论如何都希望将它们输出到新文件中
  • 你陈述的格式全错了
以下是经过上述修复的代码的更正版本:

fidInFile = fopen(filename,'r');            %# Open input file for reading
fidOutFile = fopen(['new_' filename],'w');  %# Open output file for writing
nextLine = fgets(fidInFile);                %# Get the first line of input
while nextLine >= 0                         %# Loop until getting -1 (end of file)
  nextLine = strrep(nextLine,wordA,wordB);  %# Replace wordA with wordB
  fprintf(fidOutFile,'%s',nextLine);        %# Write the line to the output file
  nextLine = fgets(fidInFile);              %# Get the next line of input
end
fclose(fidInFile);                          %# Close the input file
fclose(fidOutFile);                         %# Close the output file

您可以使用函数(它在下面调用FOPEN/FREAD/FCLOSE)以字符串形式读取整个文件,替换文本,然后使用将其一次保存到文件中


在这项任务中,您与MATLAB结婚有什么特别的原因吗?如果没有sed,它会变得非常简单:sed-i's/oldword/newword/g'filename.txt
str = fileread(filename);               %# read contents of file into string
str = strrep(str, wordA, wordB);        %# Replace wordA with wordB

fid = fopen(['new_' filename], 'w');
fwrite(fid, str, '*char');              %# write characters (bytes)
fclose(fid);