Displaying All the Related Items from an Input File

1 回表示 (過去 30 日間)
Glorit P.
Glorit P. 2020 年 5 月 29 日
コメント済み: Ameer Hamza 2020 年 6 月 1 日
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{:})
Ameer Hamza
Ameer Hamza 2020 年 6 月 1 日
I am glad to be of help!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLarge 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