Displaying All the Related Items from an Input File
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Glorit P.
am 29 Mai 2020
Kommentiert: Ameer Hamza
am 1 Jun. 2020
I am working on a program where I have to read a text file data.txt which has content like this:
Mango Guava
Banana
Pears Strawberry
Guava Watermelon
Coconut Guava
Here, Mango is related to Guava, Banana is not related to anyone, Pears is related to strawberry, Guava is related to Watermelon, and Coconut is related is Guava.
Now, the aim of the program is to check the second string of each row (if present) (i.e., Guava) with the first string in the first column (only) and if present display its relation altogether. The output of the program should be:
Mango Guava Watermelon
Banana
Pears Strawberry
Coconut Guava Watermelon
Here is what i have tried. I have read the file data and split it into 2 cell array and stored it in B and C. How should i go further to check the relations and dispay the output. Your help would be appreciated.
fid=fopen('data.txt');
tline = fgetl(fid);
tlines = cell(0,1);
while ischar(tline)
tlines{end+1,1} = tline;
tline = fgetl(fid);
end
D = regexp(tlines, '\s+', 'split');
A = vertcat(D{:});
for i= 1:length(A)
t = strsplit(A{i}) ;
b{i} = t{1} ;
end
B=b';
for j= 1:length(A)
s = strsplit(A{j,2}) ;
c{j} = s{1} ;
end
C=c';
0 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 29 Mai 2020
Bearbeitet: Ameer Hamza
am 29 Mai 2020
Try this
str = fileread('test.txt');
str_words = cellfun(@(x) {strsplit(x, ' ')}, strsplit(str, '\n'));
str_words = [vertcat(str_words{:}) repmat({''}, size(str_words, 2), 1)];
[tf, idx] = ismember(str_words(:,2), str_words(:,1));
str_words(tf, 3) = str_words(idx(tf), 2);
str_words = str_words.';
sprintf('%s %s %s\n', str_words{:})
Result
ans =
'Mango Guava Watermelon
Banana
Pears Strawberry
Guava Watermelon
Coconut Guava Watermelon
'
17 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!