0

我正在使用以下命令读取 csv 文件:

fid=fopen('test.csv');
scannedData = textscan(fid, '%4.0u%2.0u%2.0u%2.0u%2.0u%2.0u,%u,%u,%q,%q,%f,%f,%.2f,%u','whitespace','"');
fclose(fid);

问题是 textscan 不会从最后一个字段读取值并在 1 行后停止。跳过该字段,为其分配不同的类型,在 textscan 中使用许多 eof 组合,没有任何帮助。

文件中的数据如下所示:

"20100324072328","501","1","str1","str2","4.6846712","52.0159507","1.250000","128.000000"
"20100324072519","501","1","str1","str2","4.6846122","52.0159346","0.000000","128.000000"
"20100324072640","501","1","str1","str2","4.6846014","52.0159453","0.000000","128.000000"
"20100324072812","501","1","str1","str2","4.6845907","52.0159507","0.000000","96.000000"
"20100324073002","501","1","str1","str2","4.6845800","52.0159614","0.000000","128.000000"

当我尝试使用上述命令时,我想直接使用 textscan 解析第一个文件。

我不想使用读取字段%q然后解析结果数组的替代方法。

因此,我将不胜感激任何建议让 textscan 一次性完成所有操作。

谢谢。

4

1 回答 1

1

如果您想将其视为"空格,则不应使用%qwhich 需要双引号来标识完整的字符串,并且如果您将它们视为空格则无法找到它们:

fid = fopen('test.txt');
fmt = '%4u%2u%2u%2u%2u%2u%u%u%s%s%f%f%f%u';
out = textscan(fid,fmt,'Delimiter',',','Whitespace','"')
fclose(fid)

或者,我在评论中建议使用:

fmt = '"%4u%2u%2u%2u%2u%2u" "%u" "%u"%q%q"%f" "%f" "%f" "%u"';
out = textscan(fid,fmt,'Delimiter',',')

注意我如何空格" ",否则textscan()无法识别字段何时真正结束。

但是,我个人可能会将明确的日期转换为序列日期

fmt = '%s%u%u%s%s%f%f%f%u';
out = textscan(fid,fmt,'Delimiter',',','Whitespace','"')
out{1} =  datenum(out{1},'yyyymmddHHMMSS');
于 2013-08-20T12:02:14.550 回答