如何在MATLAB中将此文本文件转换为列表?

Ben*_*sen 3 file-io matlab list text-files matlab-struct

我有一个文本文件,想将其导入MATLAB并将其列为一个列表:

Person1
name = steven
grade = 11
age= 17

Person2
name = mike
grade = 9
age= 15

Person3
name = taylor
grade = 11
age= 17
Run Code Online (Sandbox Code Playgroud)

上面有几百个条目.每个都用空行分隔.我想我可以扫描文本,使每一个空白行之间的信息添加到列表中的项目.我也希望能够通过名称到每个人抬头一旦我有类似下面的列表.

我想要的东西:

x = [Person1         Person2       Person3      
     name = steven   name = mike   name = taylor
     grade = 11      grade = 9     grade = 11
     age = 17        age = 15      age = 17]
Run Code Online (Sandbox Code Playgroud)

这似乎很直接,但到目前为止我一直遇到麻烦.我可能会忽略一些事情.任何人有任何想法或建议?

gno*_*ice 5

有很多方法可以做到这一点.假设数据文件age=数据文件之间应该有空格(就像其他字段一样),你可以使用TEXTSCAN:

fid = fopen('people.txt','r');           %# Open the data file
peopleData = textscan(fid,'%s %*s %s');  %# Read 3 columns of strings per row,
                                         %#   ignoring the middle column
fclose(fid);                             %# Close the data file
Run Code Online (Sandbox Code Playgroud)

然后,你可以处理数据以下述方式来创建字段3×1结构阵列'name','grade''age':

nFields = 3;                                       %# Number of fields/person
fields = peopleData{1}(2:nFields+1);               %# Get the field names
peopleData = reshape(peopleData{2},nFields+1,[]);  %# Reshape the data
peopleData(1,:) = [];                              %# Remove the top row
peopleData(2:nFields,:) = cellfun(@str2double,...  %# Convert strings to numbers
                                  peopleData(2:nFields,:),...
                                  'UniformOutput',false);
x = cell2struct(peopleData,fields,1);              %# Put data in a structure
Run Code Online (Sandbox Code Playgroud)

以上使用函数RESHAPE,CELLFUN,STR2DOUBLECELL2STRUCT.