[英]How can i read text file and load data to an array?
I have a .txt file that follows the next format: 我有一个遵循下一格式的.txt文件:
00:00.300 ID:4 zzzzzzzzzzz
00:02.155 ID:4 aaaaaaaaaaaaa
00:04.662 ID:4 dsadasd
**00:32.283** ID:4 level **790**
00:32.155 ID:4 Sfghgfs
00:32.200 ID:4 Tsdfsdfdfsff
**00:32.205** ID:4 level **640**
00:32.206 ID:4 Sadssd
00:32.208 ID:4 asdasgsfgsgsagsa
00:32.210 ID:4 adasgx
00:32.212 ID:4 Masddasdas.
**01:40:40.698** ID:4 level **500**
So, I want to scan the file and extract the time to an array whenever appears in the line "level XXX". 因此,我想扫描文件并将时间提取到数组,只要出现在“级别XXX”行中。 After this, i want to read the correspondent level and save in another array to draw a graphic with both. 在此之后,我想读取对应的级别并保存在另一个数组中以绘制两者的图形。
I tried the functions: textscan
and strfind
but it doesn't work. 我尝试了这些函数: textscan
和strfind
但它不起作用。 Can you guys help me? 你们能帮助我吗?
You can use a regular expression: 您可以使用正则表达式:
raw = fileread('mytext.txt');
tokens = regexp(raw,'((?:\d{2}:)?\d{2}:\d{2}\.\d{3})[^\n]+level[^\d]+(\d{3})','tokens');
tokens = [tokens{:}];
timestamps = tokens(1:2:end);
levels = tokens(2:2:end);
Inspect outputs: 检查输出:
>> timestamps
timestamps =
1×3 cell array
{'00:32.283'} {'00:32.205'} {'01:40:40.698'}
>> levels
levels =
1×3 cell array
{'790'} {'640'} {'500'}
This just displays the value for the time_stamp and the level. 这只显示time_stamp和级别的值。 Feel free to pass them to whatever you want after that. 在那之后随意将它们传递给你想要的任何东西。
ff = fopen('filename.txt');
while ~feof(ff)
A = fgetl(ff);
if contains(A,'level')
time_stamp = sscanf(A,'%s ID:4 break_here') % the 'break_here' string is intended to not match the text in the file
level = sscanf(A,strcat(time_stamp,' ID:4 level %f'))
end
end
fclose(ff);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.