Displaying All the Related Items from an Input File

1 次查看(过去 30 天)
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';

采纳的回答

Ameer Hamza
Ameer Hamza 2020-5-29
编辑:Ameer Hamza 2020-5-29
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 个评论
Glorit P.
Glorit P. 2020-6-1
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{:})

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Large Files and Big Data 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by