How do I replace words in the text file?
3 次查看(过去 30 天)
显示 更早的评论
function [] = Assign5()
clc;clear
readstring = read_form();
[tag,replacement] = read_sub_tag();
newstring = replace_tags(readstring,tag,replacement);
create_output(newstring)
end
function readstring = read_form()
fname = fopen('form.txt','r');
readstring = [];
while ~feof(fname)
sline = fgets(fname);
readstring = strcat(readstring,sline);
readstring = lower(readstring);
end
fclose(fname);
end
function [tag,replacement] = read_sub_tag()
tag = [];
replacement = [];
fname = fopen('sub.txt','r');
[tag,replacement] = strtok(fgets(fname));
tag = lower(tag);
replacement = strtrim(replacement);
fclose(fname);
end
function newstring = replace_tags(readstring,tag,replacement)
newstring = [];
occurence = strfind(readstring,tag);
end
function create_output(newstring)
fname = fopen('Tongue_Twister.txt','wt');
fprintf(fname,newstring);
fclose(fname);
end
The third subfunction should replace '[what?]' in form.txt to sub.txt 'thought', what code should I enter to achieve this function? And I want it to be line up like lab5demo.txt ...
Please someone helps me out!
0 个评论
回答(1 个)
Prabhanjan Mentla
2020-11-24
Hi,
The naive approach would be to convert everything to lowercase and then replace, but the problem is in the obtained output file as every word is lowercase which is not expected with actual output (Lab5Demo.txt).
Here’s the sample code (specific to this example) that does the same job without converting into lowercase.
function [] = Assign5()
clc;clear
[tag,replacement] = read_sub_tag();
create_output(replacement);
end
function [tag,replacement] = read_sub_tag()
tag = [];
replacement = [];
fname = fopen('sub.txt','r');
[tag,replacement] = strtok(fgets(fname));
tag = lower(tag);
replacement = strtrim(replacement);
fclose(fname);
end
functioncreate_output(replacement)
Original_File = fopen('form.txt','r') ;
Modified_File = fopen('Lab5Demo.txt','w');
while ( ~feof(Original_File) )
str = fgets(Original_File);
% Compare what with any of {what,WHAT,What,......} by making case insensitive(?i)
match = regexp(str, '(?i)what(?-i)') ;
i = length(match);
while (~isempty(match) && i>0)
% In this example to replace [what?] with thought with help of indexes.
newStr = replaceBetween(str,match(i)-1,match(i)-1+6,replacement);
str = newStr;
i=i-1;
end
fprintf(Modified_File,newStr) ;
end
fclose(Original_File);
fclose(Modified_File);
end
I hardcoded the tag string to get it done as this is just a sample code. You can try making this a generalized one with the help of regex. You can also use regexprep once you’re comfortable with regex and get the whole line at once without looping for each match.
Hope this helps.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!