简体   繁体   English

如何使用 textscan 读取这个 txt 文件 matlab/octave

[英]How to use textscan to reading this txt file matlab/octave

How to use textscan to reading this txt file matlab/octave如何使用 textscan 读取这个 txt 文件 matlab/octave

Time:
11:00
Day:
2019-11-05
Company:
Hyperdrones
Drones:
Jupiter, alvalade, 20, 2000, 500.0, 20.0, 2019-11-05, 10:15
Terra, ameixoeira, 15, 1500, 400.0, 20.0, 2019-11-05, 10:20
V125, ameixoeira, 20, 2000, 350.0, 20.0, 2019-11-05, 10:20
Saturno, lumiar, 10, 1000, 600.0, 20.0, 2019-11-05, 10:30
Neptuno, lumiar, 15, 1500, 600.0, 15.0, 2019-11-05, 10:30
Mercurio, alvalade, 25, 2500, 200.0, 20.0, 2019-11-05, 10:40
Marte, campogrande, 10, 1500, 100.0, 10.0, 2019-11-05, 10:50

Assuming you want to read the matrix portion:假设您要读取矩阵部分:

C = textscan(fileID, '%s %s %d %d %f %f %{yyyy-dd-MM}D %{HH:mm}D','HeaderLines',7,'Delimiter,',')

The 7 assumes there aren't really blank lines in your file. 7 假设您的文件中没有真正的空行。 If you have blank lines, adjust that to 14 or whatever is appropriate).如果您有空行,请将其调整为 14 或任何适当的值)。

Regarding the Octave version specifically , I would recommend something like this:关于Octave版本,我会推荐这样的东西:

pkg load io                          % required for `csv2cell` function
tmp = fileread('data');              % read file as string
tmp = strsplit( tmp, '\n' );         % split on line endings to create rows
tmp = tmp(1:6);                      % keep only rows 1 to 6
Headers = struct( tmp{:} );          % create struct from comma-separated-list
Headers.Drones = csv2cell('data', 7) % use csv2cell to read csv starting from row 7

Result:结果:

Headers =
  scalar structure containing the fields:
    Time:: 1x5 sq_string
    Day:: 1x10 sq_string
    Company:: 1x11 sq_string
    Drones: 8x8 cell

Matlab does not come with an equivalent csv2cell function, but there are similar ones on matlab fileexchange; Matlab不附带等效的csv2cell function,但在 matlab 文件交换上有类似的; here's one that seems to have similar syntax as the octave version . 这是一个似乎与 octave 版本具有相似语法的版本

In general I'd use csv2cell for non-numeric csv data of this nature;一般来说,我csv2cell用于这种性质的非数字 csv 数据; it's much easier to work with than textscan.它比 textscan 更容易使用。 I'd only use textscan as a last resort for non-csv files with lines that are unusual but otherwise consistent in some way...我只会将 textscan 用作非 csv 文件的最后手段,这些文件的行不寻常但在某些方面保持一致......

PS. PS。 If your csv file ends with an empty line, csv2cell might result in an extra 'empty' cell row.如果您的 csv 文件以空行结尾, csv2cell可能会导致额外的“空”单元格行。 Remove this manually if you don't want it.如果您不想要它,请手动删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM