在Matlab中检索文本文件内容信息 [英] retriving a text file content information in Matlab

查看:375
本文介绍了在Matlab中检索文本文件内容信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt文件,其中包含300行.例如,第一行是:

I have a .txt file which includes 300 lines. For example the first line is:

ANSWER: correct: yes, time: 6.880674, guess: Lay, action: Lay, file: 16

或第二行是:

ANSWER: correct: no, time: 7.150422, guess: Put on top, action: Stir, file: 18

只有时间"和文件"值是数字,其他是字符串.

Only 'time' and 'file' values are numbers and the others are string.

我想将整个300行的正确",时间",猜测",动作"和文件"的值存储在不同的变量中(例如某些数组).

I want to store the values of "correct", "time", "guess", "action" and "file" of the whole 300 lines in the different variables (like some arrays).

如何在Matlab中做到这一点?

How can I do this in the Matlab?

推荐答案

选项1:

您可以将 textscan 与以下 formatSpec :

formatSpec = 'ANSWER: correct:%s time:%f guess:%s action:%s file: %f';
data = textscan(fileID,formatSpec,'Delimiter',',');

其中fileID fopen .

另一种选择是将 readtable 与上面的格式(直接使用文件名,没有fileID):

Another option is to use readtable, with the formatting above (directly with the file name, no fileID):

data = readtable('53485991.txt','Format',formatSpec,'Delimiter',',',...
    'ReadVariableNames',false);
% the next lines are just to give the table variables some meaningful names:
varNames = strsplit(fmt,{'ANSWER',':','%s',' ','%f'});
data.Properties.VariableNames = varNames(2:end-1);

结果(忽略这些值,因为我在玩该示例时将其弄乱了一点):

The result (ignore the values, as I messed that example a little bit while playing with it):

data =
  4×5 table
    correct     time          guess         action    file
    _______    ______    _______________    ______    ____
    'yes'      6.8888    'Lay'              'Lay'      16 
    'no'       7.8762    'Put on top'       'Stir'     18 
    'no'       7.1503    'Put on bottom'    'Stir'      3 
    'no'        7.151    'go'               'Stir'    270 

选项2的优点在于,表为textscan的输出)相比,这是保存这些数据的一种更为方便的方式.

The advantage in option 2 is that a table is a much more convenient way to hold these data than a cell array (which is the output of textscan).

这篇关于在Matlab中检索文本文件内容信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆