Displaying All the Related Items from an Input File

1 Ansicht (letzte 30 Tage)
Glorit P.
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';

Akzeptierte Antwort

Ameer Hamza
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
Glorit P.
Glorit P. am 1 Jun. 2020
Hi Ameer,
For some strange reason, i do not know why it is giving me different output for the same code.
I made slight modification to your code and it is giving me the same output as required now.
Thank you very much for all your help and time. Much appreciated.
Here is a code that worked for me.
fid=fopen('data1.txt');
tline = fgetl(fid);
str = cell(0,1);
while ischar(tline)
str{end+1,1} = tline;
tline = fgetl(fid);
end
D = regexp(str, '\s+', 'split');
A = vertcat(D{:});
while true
[tf, idx] = ismember(A(:,end), A(:,end-1));
A(tf, end+1) = A(idx(tf), end);
A(~tf, end) = deal({''});
if all(cellfun(@isempty, A(:,end)))
break;
end
end
A(:,end) = [];
A = A.';
fprintf([repmat('%s ', 1, size(A,1)) '\n'], A{:})
Ameer Hamza
Ameer Hamza am 1 Jun. 2020
I am glad to be of help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by