Filter löschen
Filter löschen

Replacing a string in the txt file from retrieving from a csv file

3 Ansichten (letzte 30 Tage)
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 Kommentare
Joseph Muguro
Joseph Muguro am 23 Mär. 2021
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
Denxybel Montinola am 23 Mär. 2021

Hi, thanks for that. My main concern ,at the moment, is that the strings in my code didn’t match any of it in the txt file. Maybe there is something wrong in my string construction

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Cris LaPierre
Cris LaPierre am 23 Mär. 2021
Bearbeitet: Cris LaPierre am 24 Mär. 2021
I'd break this into a couple steps.
  1. Import the raw data correctly
  2. Keep the data in a table
  3. Modify the string to match the format in Template.txt (remove "DoseAt" from beginning, ".csv" from the end)
  4. Use discretize to create a new table column with value of blue/red coming from value in column 9.
  5. Use readlines to load the entire file to a string array (requires R2020b).
  6. 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.
  7. 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 Kommentare
Denxybel Montinola
Denxybel Montinola am 24 Mär. 2021

Thank you for this, it works well! It’s quite advance for me but will learn from this.

Cris LaPierre
Cris LaPierre am 24 Mär. 2021
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by