collect data from a text file without a uniform structure
2 次查看(过去 30 天)
显示 更早的评论
Hi everybody, I am making effort to solve this Problem with Matlab :
I have a text (txt-file or a String) describing pats of a car with different parts like this:
!type wheel,battery,glass,motor
!part wheel-w1
!price 50
!weight 23
!number 2
!end part wheel-w1
!part wheel-w2
!price 60
!weight 23
!number 2
!end part wheel-w2
!part battery-b1
!price 200
!weight 15
!number 1
!end part battery-b1
!part glass-g1
!price 300
!weight 12
!number 1
!end part glass-g1
!part glass-g2
!price 200
!weight 5
!number 4
!end part glass-g2
!part motor-m1
!price 5000
!weight 50
!number 1
!guarantee 5
!upgrade 1
!end part motor-m1
I want to collect all the specifications of every part by using the function "textscan" . But the textpart for the part "motor-m1" has two lines more than the others textparts.
You see, that the other parts do not have the lines:
!guarantee
!upgrade
and we can consider these specifications are 0 for the other parts. so what should I do to receive a result like this (the blanks can be filled with number 0) :
partname price W. Nr. G. U.
wheel-w1 50 23 2
wheel-w2 60 23 2
baterry-b1 200 15 1
glass-g1 300 12 1
glass-g2 200 5 4
motor-m1 5000 50 1 5 1
Thanks for your help in advance !
0 个评论
采纳的回答
Vivek Selvam
2013-11-7
编辑:Vivek Selvam
2013-11-7
Since the file is not uniform, you would need a loop to process line by line.
Following is a way you can try:
filename = 'txtFile.txt';
fileID = fopen(filename);
formatSpec = '%s %s %s'; % read in # cell columns
data = textscan(fileID,formatSpec);
fclose(fileID);
i = 2;
partNum = 0;
for i = 1:numel(data{1,1})
switch data{1,1}{i}
case '!part'
partNum = partNum + 1;
part(partNum).name = data{1,2}{i};
part(partNum).price = 0;
part(partNum).weight = 0;
part(partNum).number = 0;
part(partNum).guarantee = 0;
part(partNum).upgrade = 0;
case '!price'
part(partNum).price = str2num(data{1,2}{i});
case '!weight'
part(partNum).weight = str2num(data{1,2}{i});
case '!number'
part(partNum).number = str2num(data{1,2}{i});
case '!guarantee'
part(partNum).guarantee = str2num(data{1,2}{i});
case '!upgrade'
part(partNum).upgrade = str2num(data{1,2}{i});
end
end
openvar part
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!