Replacing a string in the txt file from retrieving from a csv file
3 次查看(过去 30 天)
显示 更早的评论
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
...
采纳的回答
Cris LaPierre
2021-3-23
编辑:Cris LaPierre
2021-3-24
I'd break this into a couple steps.
- Import the raw data correctly
- Keep the data in a table
- Modify the string to match the format in Template.txt (remove "DoseAt" from beginning, ".csv" from the end)
- Use discretize to create a new table column with value of blue/red coming from value in column 9.
- Use readlines to load the entire file to a string array (requires R2020b).
- With everything loaded in a string array, you now only need 1 loop. Loop through the strings in excel, searching for and replacing them in the string array with a string containing the color. Use contains to search and replace to add the color.
- Use fprintf to write the file since fwrite doesn't support non-scalar string arrays.
Putting it all together, here's some sample code.
% Load the data, removing empty rows and columns
opts = detectImportOptions("PercentageDifference_Template.csv","ReadVariableNames",false,"Range",3);
opts.ExtraColumnsRule = "ignore";
opts = setvartype(opts,"Var1","string");
excel = readtable('PercentageDifference_Template.csv',opts);
excel(~contains(excel.Var1,"DoseAtDemoSphere"),:)=[]
% Extract the string to use in searching
excel.name = extractBetween(excel.Var1,"DoseAt",".csv")
% Discretize values in column 9 to determine color: blue if <=0, red if >0
excel.color=discretize(excel.Var9,[-inf,0,inf],'categorical',["blue","red"],"IncludedEdge","right")
% Load Template file
C = readlines('template.txt');
% Loop through names in excel, find them in string array
% update value in string array to include color
s1 = "s:Ge/";
s2 = "/Color";
for r = 1:height(excel)
name = s1 + excel.name(r) + s2;
ind = contains(C,name);
C(ind) = replace(C(ind),name,name + " = " + '"' + string(excel.color(r)) + '"');
end
% Write the modified data to a new test file
Modified_File = fopen('template_1.txt','w') ;
fprintf(Modified_File,'%s\n',C);
fclose(Modified_File);
2 个评论
Cris LaPierre
2021-3-24
Take it a line at a time, and use the documentation to learn what each of the functions does. The code itself is fairly simple. It is the functions that are doing all the advanced manipulation.
更多回答(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!