问题
I have a text file that looks like so:
A B C
1 2 3
(This is just a minimal example of what I actually have. My actual files are HUGE and vary in number of rows.)
I would like to load in this file into Octave. However, the file contains letters, rather than just numbers. When I'm trying to apply the load function, I get errors, and I guess this is because the load function only accepts numbers. What function should I use instead?
回答1:
Call fopen, fscanf, and fclose. The format string must be different for lines containing only letters (like '%s\t%s\t%s'
), and for those which contain only numbers (like '%g\t%g\t%g'
). You can read lines of identical structure with a single fprintf call.
Example file (data.txt):
A B C
D E F
1 2 3
4 5 6
7 8 9
10 11 12
Suppose that we know in advance that the file contains 3 columns, and 2 lines with characters at the beginning:
fid = fopen('data.txt', 'r');
[x, nx] = fscanf(fid, '%s\t%s\t%s', [3, 2]);
[y, ny] = fscanf(fid, '%g\t%g\t%g', [3, Inf]);
fclose(fid);
The lines with the characters will be in x'
, and the lines with numbers will be contained by y'
.
来源:https://stackoverflow.com/questions/8198428/load-a-text-file-containing-both-numbers-and-letters