根据条件将文本文件内容读入矩阵

Read text file content into matrix based on condition

我有一个这种格式的文本文件:

Food
Fruits1     [heading]
    Apple    [value]
    Mango    [value]
    Orange   [value]
Veg1        [heading]
    Potato   [value]
    Lettuce  [value]

我想将其加载到 Octave 中作为这种格式的矩阵:

----------------------------------------------------------------------
Item | Fruits1 | Apple | Mango | Orange | Veg1 | Potato | Lettuce
----------------------------------------------------------------------
     |         |       |       |        |      |        |         
----------------------------------------------------------------------

因此,我需要一个大小为 2x(n+m+1) 的矩阵;其中 n = [标题] 的数量,m = [值] 的数量。

如何使用fgetl从文本文件中读取每一行并存储到满足上述条件的矩阵中?有更好的想法吗?

谢谢!

编辑:代码:-

fid = fopen('food.txt','r');
num = 1;
  if (fid < 0) 
    printf('Error:could not open file\n')
  else
    while ~feof(fid),
    line = fgetl(fid);
    arr=[line;];     
    num=num+1;
    end;
        fclose(fid)
  end; 

无法使用矩阵,因为您的字符串长度不同。只能将其放入单元格中。但我会推荐一个结构化列表。

fid = fopen('list.txt');

while 1
  tmp = fgetl(fid);
  if ~ischar(tmp)
    % end of file
    break
  end

  if strcmp(deblank(tmp), 'Food')
    # this can't be empty
    listObj.('item') = 'Food';
  else
    tmp = cell2mat(regexp(deblank(tmp),'(\w+)','tokens'));
    if strcmp(tmp{1,2}, 'heading')
      head = tmp{1,1};
    else
      listObj.(head).(tmp{1,1}) = str2double(tmp{1,2});
    end
  end
end

您可以更好地访问它。

>> Whosebug
>> listObj
listObj =

  scalar structure containing the fields:

    item = Food
    Fruits1 =

      scalar structure containing the fields:

        Apple =                    3
        Mango =                    4
        Orange =                    1

    Veg1 =

      scalar structure containing the fields:

        Potato =                    8
        Lettuce =                    0


>> listObj.Fruits1.Apple
ans =                    3
>> listObj.Veg1.Lettuce
ans =                    0
>>

但是请注意您的输入文件,它必须严格格式化。我的示例文件如下所示

Food
Fruits1     [heading]
    Apple    3
    Mango    4
    Orange   1
Veg1        [heading]
    Potato   8
    Lettuce  0