将wordS替换为文本中的wordS,然后将其保存在新文件中。 MATLAB

时间:2010-11-15 19:01:10

标签: matlab file-io

我怎样才能编写一个函数来接受以下内容: filename :(对应于文件名的字符串) wordA和wordB:它们都是两个没有空格的字符串

该功能应该这样做: 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

2 个答案:

答案 0 :(得分:4)

您可以使用FILEREAD函数(下面调用FOPEN / FREAD / FCLOSE)读取字符串中的整个文件,替换文本,然后使用FWRITE将其全部保存到文件中。

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);

答案 1 :(得分:1)

要解决的一些问题:

  • 使用函数STRREP而不是自己解析文本会更容易。
  • 我会使用FGETS代替FGETL将换行符保留为字符串的一部分,因为无论如何你都想将它们输出到新文件中。
  • FPRINTF声明的格式完全错误。

以下是具有上述修复程序的代码的更正版本:

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