Replacing a string in the txt file from retrieving from a csv file
이전 댓글 표시
Hello, I am trying to debug my code but it seems that my mind is toast in finding it. I am trying to replace a certain sentence in my txt file from the data that I have in my csv file (please see attached file). Column 1 in my csv file containts the name of the geometry, and in column 2 contains some numbers which will be categorized as either red or blue.
The goal of the code is to replace this exact string in the txt file from,
s:Ge/(name of the geometry)/Color
to,
s:Ge/(name of the geometry)/Color = "(red/blue)"
Here is the code that I come up with and I think the error is somewhere in for-while loop statement:
Original_File = fopen('template.txt','r') ;
Modified_File = fopen('template_1.txt','w') ;
excel = readtable('/Applications/PercentageDifference_Template.csv');
%getting the name of the sphere in column 1 starting from row 3 - 514
excelname = excel(3:514, 1);
excelname = table2cell(excelname);
excelname = string(excelname);
excelname = erase(excelname,".csv");
%getting the numbers out from column 9
excelnum = excel(3:514, 9);
excelnum = table2cell(excelnum);
excelnum = cell2mat(excelnum);
%conditional statement: when the number is greater than 0 then it is red or
%else it is blue
for i = 1:numel(excelnum)
if excelnum(i)>0
color = 'red';
else
color = 'blue';
end
while( ~feof(Original_File) )
% read line from original text file
% in here the complete string should be s:Ge/(name of the
% excelnum(i))/Color
str = fgets(Original_File) ;
s1 = 's:Ge/';
s2 = '/Color';
name = s1 + excelname(i) + s2;
% match line to regular expression to determine if replacement needed
match = regexp(str, name, 'match');
% if old word is to be replaced then change it to s:Ge/(name of the
% excelnum(i))/Color = "(red/blue)"
if ( ~isempty(match) )
str = strrep(str, name, name + '=' + '"' + color + '"');
end
fwrite(Modified_File,str) ;
end
end
댓글 수: 2
Joseph Muguro
2021년 3월 23일
You are not saving color field anywhere...
color= strings(numel(excelnum),1);% initialize color array
for i = 1:numel(excelnum)
if excelnum(i)>0
color(i) = 'red';
else
color(i) = 'blue';
end
...
Denxybel Montinola
2021년 3월 23일
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!