文本文档的信息多是按照行的格式读写的,因此在读取时对提取到每行的文本信息进行关键字的对比找到指定行,然后利用正则表达式提取相应的信息即可。
文本信息示例
positions bitstream size 550216 B (12.5996 bpp)
positions processing time (user): 8.203 s
colors bitstream size 9459 B (0.216605 bpp)
colors processing time (user): 5.984 s
reflectances bitstream size 1706 B (0.0390663 bpp)
reflectances processing time (user): 0.64 s
1. MATLAB读取文本文档
fidin = fopen('encoder.txt','r');
while ~feof(fidin)
tline = fgetl(fidin);
end
2. strncmp函数定位行信息
strncmp(tline,'positions bitstream',15)
对比前两个字符串中前15个字符是否一致,一致返回非零结果,可根据此结果执行信息提取操作。
if strncmp(tline,'positions bitstream',15)
Gbit = regexp(tline,'\d*\.?\d*','match');
end
3. strfind函数定位行信息
if strfind(tline,'h.r,PSNR F')
hRpsnr = regexp(tline,'\d*\.\d*','match');
end
strfind会在tline查找是否含有用户输入的字符串,并返回第一个字母在tline的位置,同样可以作为进一步操作的判据。
4. regexp正则表达式
regexp(tline,'\d*\.\d*','match');
regexp(tline,'\d*\.?\d*','match');
第一个提取tline中的浮点数数值,第二个提取tline中整数、浮点数两种数值,可根据数据类型自行选择。
例如:
tline = 'positions bitstream size 550216 B (12.5996 bpp)';
Gbit1 = regexp(tline,'\d*\.\d*','match');
Gbit2 = regexp(tline,'\d*\.?\d*','match');
Gbit1 = {'12.5996'}
Gbit2 = {'550216' '12' '5996'}
正则表达式返回的结果为元胞数组类型,所有的数据都是字符串类型,如果要对数据进行操作可以利用str2num转换为数值类型,如果要写入Excel文档则需要通过num2str再转换回来。