【问题标题】:Read fields from text file and store them in a structure从文本文件中读取字段并将它们存储在结构中
【发布时间】:2026-01-24 01:55:01
【问题描述】:

我正在尝试读取如下所示的文件:

Data Sampling Rate: 256 Hz
*************************

Channels in EDF Files:
**********************
Channel 1: FP1-F7
Channel 2: F7-T7
Channel 3: T7-P7
Channel 4: P7-O1

File Name: chb01_02.edf

File Start Time: 12:42:57

File End Time: 13:42:57 

Number of Seizures in File: 0

File Name: chb01_03.edf

File Start Time: 13:43:04

File End Time: 14:43:04

Number of Seizures in File: 1

Seizure Start Time: 2996 seconds

Seizure End Time: 3036 seconds

到目前为止,我有这个代码:

fid1= fopen('chb01-summary.txt')
data=struct('id',{},'stime',{},'etime',{},'seizenum',{},'sseize',{},'eseize',{});
if fid1 ==-1
    error('File cannot be opened ')
end
tline= fgetl(fid1);
while ischar(tline)
    i=1;
    disp(tline);
end

我想使用regexp 来查找表达式,所以我做到了:

line1 = '(.*\d{2} (\.edf)' 
data{1} = regexp(tline, line1);
tline=fgetl(fid1);
time = '^Time: .*\d{2]}: \d{2} :\d{2}' ;
data{2}= regexp(tline,time);
tline=getl(fid1);
seizure = '^File: .*\d';
data{4}= regexp(tline,seizure);
if data{4}>0
    stime = '^Time: .*\d{5}'; 
    tline=getl(fid1);
    data{5}= regexp(tline,seizure);
    tline= getl(fid1);
    data{6}= regexp(tline,seizure);
end

我尝试使用循环查找文件名开头的行:

for (firstline<1) || (firstline>1 )
    firstline= strfind(tline, 'File Name') 
    tline=fgetl(fid1);
end 

现在我被难住了。

假设我在有信息的那一行,如何用regexp 存储信息?运行一次代码后,我得到了一个空数组 data...

提前致谢。

【问题讨论】:

    标签: regex matlab text-parsing


    【解决方案1】:

    我发现首先使用textscan 将行读入单元阵列是最简单的:

    %// Read lines as strings
    fid = fopen('input.txt', 'r');
    C = textscan(fid, '%s', 'Delimiter', '\n');
    fclose(fid);
    

    然后在其上应用regexp 以进行其余操作:

    %// Parse field names and values
    C = regexp(C{:}, '^\s*([^:]+)\s*:\s*(.+)\s*', 'tokens');
    C = [C{:}];                          %// Flatten the cell array
    C = reshape([C{:}], 2, []);          %// Reshape into name-value pairs
    

    现在您有了一个包含字段名称及其对应(字符串)值的元胞数组C,您所要做的就是以正确的语法将其插入struct(在这种情况下使用comma-separated list) .请注意,字段名称中包含空格,因此在使用它们之前需要注意这一点(例如将它们替换为下划线):

    C(1, :) = strrep(C(1, :), ' ', '_'); %// Replace spaces with underscores
    data = struct(C{:});
    

    这是我从您的输入文件中得到的:

    data =
    
                Data_Sampling_Rate: '256 Hz'
                         Channel_1: 'FP1-F7'
                         Channel_2: 'F7-T7'
                         Channel_3: 'T7-P7'
                         Channel_4: 'P7-O1'
                         File_Name: 'chb01_03.edf'
                   File_Start_Time: '13:43:04'
                     File_End_Time: '14:43:04'
        Number_of_Seizures_in_File: '1'
                Seizure_Start_Time: '2996 seconds'
                  Seizure_End_Time: '3036 seconds'
    

    当然,可以通过将所有相关数字转换为数值、将“频道”字段组合在一起等来进一步美化它,但我将把这个留给你。祝你好运!

    【讨论】:

      最近更新 更多