使用 matlab 忽略文本文件中间的 header 行
Ignoring header lines in the middle of the text file using matlab
我有一个包含多个观察部分的文本文件。每次,当新的观察开始时,文件都有一些关于数据的信息(比如文件的 header)。
当我使用textscan
时,我只能阅读第一部分。比如数据排列如下:
1993-01-31 17:00:00.000 031 -61.00
1993-01-31 18:00:00.000 031 -55.00
1993-01-31 19:00:00.000 031 -65.00
Format
Source of Data
Station Name
Data Interval Type 1-hour
Data Type Final
1993-02-01 00:00:00.000 032 -83.00
1993-02-01 01:00:00.000 032 -70.00
1993-02-01 02:00:00.000 032 -64.00
从上面看,我只想读取以“1993”开头的数据行,忽略中间的文本块。
如您所见,textscan
在无法再解析输入时停止读取。您实际上可以利用它来发挥自己的优势。例如,在您的情况下,您知道每个 "good" 数据集之间有 5 行垃圾。所以我们可以 运行 textscan
一次得到第一组,然后 运行 连续多次(Headerlines
设置为 5 以忽略这 5 行)得到每个"good" 文件中的数据集。然后连接所有数据。
这是有效的,因为当您将 textscan
与文件标识符一起使用时,它 不会 将文件标识符倒回到它之后的文件开头 returns.它把它留在它停止解析它的地方。因此,对 textscan
的下一次调用将从您停止的地方开始(减去您指定的任何 header 行)
fid = fopen(filename, 'r');
% Don't ignore any lines but read until we stop
data = textscan(fid, formatspec);
% Repeat until we hit the end of the file
while ~feof(fid)
% Skip 5 lines and read until we can't read anymore
newdata = textscan(fid, formatspec, 'HeaderLines', 5);
% Append to existing data
data = cellfun(@(x, y)cat(1, x, y), data, newdata, 'uni', 0);
end
fclose(fid)
我有一个包含多个观察部分的文本文件。每次,当新的观察开始时,文件都有一些关于数据的信息(比如文件的 header)。
当我使用textscan
时,我只能阅读第一部分。比如数据排列如下:
1993-01-31 17:00:00.000 031 -61.00
1993-01-31 18:00:00.000 031 -55.00
1993-01-31 19:00:00.000 031 -65.00
Format
Source of Data
Station Name
Data Interval Type 1-hour
Data Type Final
1993-02-01 00:00:00.000 032 -83.00
1993-02-01 01:00:00.000 032 -70.00
1993-02-01 02:00:00.000 032 -64.00
从上面看,我只想读取以“1993”开头的数据行,忽略中间的文本块。
如您所见,textscan
在无法再解析输入时停止读取。您实际上可以利用它来发挥自己的优势。例如,在您的情况下,您知道每个 "good" 数据集之间有 5 行垃圾。所以我们可以 运行 textscan
一次得到第一组,然后 运行 连续多次(Headerlines
设置为 5 以忽略这 5 行)得到每个"good" 文件中的数据集。然后连接所有数据。
这是有效的,因为当您将 textscan
与文件标识符一起使用时,它 不会 将文件标识符倒回到它之后的文件开头 returns.它把它留在它停止解析它的地方。因此,对 textscan
的下一次调用将从您停止的地方开始(减去您指定的任何 header 行)
fid = fopen(filename, 'r');
% Don't ignore any lines but read until we stop
data = textscan(fid, formatspec);
% Repeat until we hit the end of the file
while ~feof(fid)
% Skip 5 lines and read until we can't read anymore
newdata = textscan(fid, formatspec, 'HeaderLines', 5);
% Append to existing data
data = cellfun(@(x, y)cat(1, x, y), data, newdata, 'uni', 0);
end
fclose(fid)