将复杂格式的.txt文件读入Matlab
我有一个txt文件,我想读入Matlab。数据格式如下:将复杂格式的.txt文件读入Matlab,matlab,textscan,Matlab,Textscan,我有一个txt文件,我想读入Matlab。数据格式如下: term2 2015-07-31-15_58_25_612 [0.9934343, 0.3423043, 0.2343433, 0.2342323] term0 2015-07-31-15_58_25_620 [12] term3 2015-07-31-15_58_25_625 [2.3333, 3.4444, 4.5555] ... 如何用以下方式读取这些数据 name = [term2 term0 term3] or namenum
term2 2015-07-31-15_58_25_612 [0.9934343, 0.3423043, 0.2343433, 0.2342323]
term0 2015-07-31-15_58_25_620 [12]
term3 2015-07-31-15_58_25_625 [2.3333, 3.4444, 4.5555]
...
如何用以下方式读取这些数据
name = [term2 term0 term3] or namenum = [2 0 3]
time = [2015-07-31-15_58_25_612 2015-07-31-15_58_25_620 2015-07-31-15_58_25_625]
data = {[0.9934343, 0.3423043, 0.2343433, 0.2342323], [12], [2.3333, 3.4444, 4.5555]}
我试图以这种方式使用textscan
“术语%d%s[%f,%f..]”,但对于最后一个数据部分,我无法指定长度,因为它们不同。那我怎么读呢?我的Matlab版本是R2012b
如果有人能帮上忙,请提前多谢 可能有一种方法可以在一次传递中完成,但对我来说,这类问题更容易用两次传递的方法进行排序
- 第1步:根据列的类型(字符串、整数等)以常量格式读取所有列,并读取单独列中的非常量部分,该部分将在第二步中处理
- 第二关:根据不规则栏的特殊性处理不规则栏
%% // read file
fid = fopen('Test.txt','r') ;
M = textscan( fid , 'term%d %s %*c %[^]] %*[^\n]' ) ;
fclose(fid) ;
%% // dispatch data into variables
name = M{1,1} ;
time = M{1,2} ;
data = cellfun( @(s) textscan(s,'%f',Inf,'Delimiter',',') , M{1,3} ) ;
发生了什么:第一条
textscan
指令读取整个文件。在格式说明符中:
读取文本表达式术语%d
后的整数'term'
读取表示日期的字符串%s
忽略一个字符(忽略字符%*c
)'['
读取所有内容(作为字符串),直到找到字符%[^]]
']'
忽略所有内容,直到下一个换行符(%*[^\n]
)为止。(不捕获最后一个'\n'
']'
M
的第三列包含不同长度的字符串,其中包含不同数量的浮点数。我们与另一列结合使用,读取每个单元格中的数字,并返回一个包含double:
奖金:
如果希望时间也是一个数值(而不是字符串),请使用以下代码扩展名:
%% // read file
fid = fopen('Test.txt','r') ;
M = textscan( fid , 'term%d %f-%f-%f-%f_%f_%f_%f %*c %[^]] %*[^\n]' ) ;
fclose(fid) ;
%% // dispatch data
name = M{1,1} ;
time_vec = cell2mat( M(1,2:7) ) ;
time_ms = M{1,8} ./ (24*3600*1000) ; %// take care of the millisecond separatly as they are not handled by "datenum"
time = datenum( time_vec ) + time_ms ;
data = cellfun( @(s) textscan(s,'%f',Inf,'Delimiter',',') , M{1,end} ) ;
这将为您提供一个带有Matlab时间序列号(通常比字符串更易于使用)的数组time
。要显示序列号仍然代表正确的时间,请执行以下操作:
>> datestr(time,'yyyy-mm-dd HH:MM:SS.FFF')
ans =
2015-07-31 15:58:25.612
2015-07-31 15:58:25.620
2015-07-31 15:58:25.625
对于这种复杂的字符串解析情况,最好使用regexp
。在这种情况下,假设您在data.txt文件中有数据,下面的代码应该满足您的要求:
txt = fileread('data.txt')
tokens = regexp(txt,'term(\d+)\s(\S*)\s\[(.*)\]','tokens','dotexceptnewline')
% Convert namenum to numeric type
namenum = cellfun(@(x)str2double(x{1}),tokens)
% Get time stamps from the second row of all the tokens
time = cellfun(@(x)x{2},tokens,'UniformOutput',false);
% Split the numbers in the third column
data = cellfun(@(x)str2double(strsplit(x{3},',')),tokens,'UniformOutput',false)
对我来说太有用了!非常感谢你非常详细的回答!