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

标签 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);

然后,通过正则表达式,我读取了每个出现的 (START_DLC/END_DLC) block :

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

目的是将每个 START_DLC/END_DLC block 之间的文本内容存储在一个结构化单元格(应该称为 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, 弗朗切斯科

最佳答案

到目前为止,您的代码没有问题。不过有一件事,我会将您对 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×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'}

关于regex - 将文本文件存储在结构化数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12247235/

相关文章:

bash ->& 是什么意思?

C++ 文件 IO - 找不到文件 IO 相关内容的方法

java - 过滤器列表 : Begin by. .. Android Studio

javascript - Express.js 路由器中的正则表达式

geolocation - 使用 Matlab 在世界地图上绘制地理位置

excel - matlab使用activex接口(interface)自动保存excel文件

javascript - 构建此 JavaScript 正则表达式的困难

javascript - 替换两个标记之间的 URL 中的 ID

matlab - matlab 有三元运算符吗?

c# - 在 C# 中以独占模式打开文件