在结构化数组中存储文本文件

时间:2012-09-03 11:46:15

标签: regex matlab io

我有一个结构良好的输入文本文件:

START_PARAMETERS
C:\Users\admin\Desktop\Bladed_wind_generator\_wind
C:\Users\admin\Desktop\Bladed_wind_generator\reference_v_4_2.$PJ
END_PARAMETERS
---------------------------------------------------------------------------
START_DLC1-2
4 6 8 10 12 14 16 18 20 22 24 26 28 29
6
8192
600
END_DLC1-2
---------------------------------------------------------------------------
START_DLC6-1
44.8
30
8192
600
END_DLC6-1
---------------------------------------------------------------------------
START_DLC6-4
3 31 33 35
6
8192
600
END_DLC6-4
---------------------------------------------------------------------------
START_DLC7-2
2 4 6 8 10 12 14 16 18 20 22 24 
6
8192
600
END_DLC7-2
---------------------------------------------------------------------------

目前我用这种方式阅读:

clc,clear all,close all

f = fopen('inp.txt','rt');  % Read Input File
C = textscan(f, '%s', 'Delimiter', '\r\n');
C = C{1}; % Store Input File in a Cell
fclose(f);

然后,通过regexp我读取(START_DLC / END_DLC)块的每次出现:

startIndx = regexp(C,'START_DLC','match');
endIndx = regexp(C,'END_DLC','match');

目的是在结构化单元格中的每个START_DLC / END_DLC块之间存储文本内容(应该称为store_DLCs)。结果必须是(例如DLC1-2):

DLC1-2
4 6 8 10 12 14 16 18 20 22 24 26 28 29
6
8192
600

依此类推,直到DLC7-2。

你能不能给我一些提示如何继续?

我提前感谢你们。

BR, 弗朗西斯

1 个答案:

答案 0 :(得分:2)

到目前为止你的代码还可以。但有一件事,我会稍微改变你对startIndxendIndx的计算结果如下:

startIndx = find(~cellfun(@isempty, regexp(C, 'START_DLC', 'match')));
endIndx = find(~cellfun(@isempty, regexp(C, 'END_DLC', 'match')));

这样你就可以获得实际的索引(为了方便起见,我将它们转换到了这里),如下所示:

startIndx =

     6    13    20    27


endIndx =

    11    18    25    32

我还会添加一个断言来检查输入的完整性:

assert(all(size(startIndx) == size(endIndx)))

现在,如上所述计算所有指数,您可以继续将数据提取到单元格中:

extract_dlc = @(n)({C{startIndx(n):endIndx(n) - 1}});
store_DLCs = arrayfun(extract_dlc, 1:numel(startIndx), 'UniformOutput', false)

要“修复”每个单元格的名称(首先是条目),您可以这样做:

fix_dlc_name = @(x){strrep(x{1}, 'START_', ''), x{2:end}};
store_DLCs = cellfun(fix_dlc_name, store_DLCs,  'UniformOutput', false);

此代码应用于您的示例输入将产生1 x 4单元格的单元格数组:

store_DLCs =

    {'DLC1-2', '4 6 8 10 12 14 16 18 20 22 24 26 28 29', '6', '8192', '600'}  
    {'DLC6-1', '44.8', '30', '8192', '600'}   
    {'DLC6-4', '3 31 33 35', '6', '8192', '600'}   
    {'DLC7-2', '2 4 6 8 10 12 14 16 18 20 22 24', '6', '8192', '600'}
相关问题