[英]How to read a csv file with varying number of columns in Octave
I would like to read selected columns of string data in a csv file in which the total number of columns varies from line to line. 我想读取csv文件中字符串数据的选定列,该列的总行数在行与行之间有所不同。 Let's say the content of the csv file is as follows:
假设csv文件的内容如下:
line 1: a1,b1,c1,d1,e1
line 2: a2,b2,c2
line 3: a3,b3,c3,d3
I would like to read the 1st column into variable a and the second column into variable b with the expectation of the following values for a and b: 我希望将第一列读入变量a,将第二列读入变量b,期望a和b的值如下:
a[1,1] = a1, a[2,1] = a2, a[3,1] = a3
b[1,1] = b1, b[2,1] = b2, b[3,1] = b3
I tried using textread with the format specifiers matching just the desired columns: 我尝试使用textread和仅与所需列匹配的格式说明符:
[a,b] = textread('SampleFile.csv','%s%s','delimiter',',')
but that generated erroneous results: 但这产生了错误的结果:
a[1,1] = a1, a[2,1] = c1, a[3,1] = e1, a[4,1] = b2, a[5,1] = b3, a[6,1] = d3
b[1,1] = b2, b[2,1] = d1, b[3,1] = a2, b[4,1] = a3, b[5,1] = c3, b[6,1] =
I also tried using textread with the format specifiers matching the maximum number of columns using dummy variables for the unwanted columns: 我还尝试将textread与格式说明符匹配,以对不需要的列使用伪变量来匹配最大列数:
[a,b,dummy1,dummy2,dummy3] = textread('SampleFile.csv','%s%s%s%s%s','delimiter',',')
but that also generated erroneous results: 但这也会产生错误的结果:
a[1,1] = a1, a[2,1] = a2, a[3,1] = d3
b[1,1] = b2, b[2,1] = b2, b[3,1] =
Is there a way to capture just the desired columns using either the textread command or another approach? 有没有一种方法可以使用textread命令或其他方法来仅捕获所需的列?
I am running Octave 3.8.0 on Mac OS 10.9.5. 我在Mac OS 10.9.5上运行Octave 3.8.0。
Your output is expected because it's exactly mimics the example from the function documentation : 您的输出是预期的,因为它完全类似于功能文档中的示例:
Assume a data file like:
假设数据文件如下:
1 a 2 b1 a 2 b
3 c 4 d3 c 4 d
5 e5 e
[a, b] = textread (f, "%f %s")
returns two columns of data, one with doubles, the other a cellstr array:
返回两列数据,一列为双精度,另一列为cellstr数组:
a = [1; 2; 3; 4; 5]
b = {"a"; "b"; "c"; "d"; "e"}
You have to read your text file line by line to do what you want: 您必须逐行阅读文本文件才能执行所需的操作:
f = fopen ("test.txt");
c1 = {};
c2 = {};
while (l = fgetl (f)) != -1
[a b] = strread (l, "%s %s");
c1 = cat (1, c1, a{1});
c2 = cat (1, c2, b{1});
endwhile
fclose (f);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.