读取带有多个空格的文本文件

时间:2018-10-12 13:14:41

标签: csv import scilab

到目前为止我想做并成功完成的事情

我正在使用Scilab 5.5.2,我编写了一个通用的交互式脚本,该脚本应该将文本文件(* .csv,* .txt)中的数字数据读入矩阵变量中。应该设计得足够通用以直接读取大多数文本数据文件。

我成功使用了csvRead。它非常灵活,可以读取几乎所有带有数据的文本文件,甚至包括标头等。

问题

但是如果文本文件包含多个空格作为数据定界符,则csvRead将失败。这意味着它需要每个单个空格作为分隔符,并且会被不同数量的列弄糊涂。

fscanfMat可以在没有空白行的情况下正常工作,并且没有多个空白行,但是文件通常看起来像这样:

MONTHLY MEAN CENTRAL ENGLAND TEMPERATURE (DEGREES C)                                     
1659-1973 MANLEY (Q.J.R.METEOROL.SOC., 1974)                                             
1974 ON PARKER ET AL. (INT.J.CLIM., 1992)                                                
PARKER AND HORTON (INT.J.CLIM., 2005)                                                    


           JAN   FEB   MAR   APR   MAY   JUN   JUL   AUG   SEP   OCT   NOV   DEC     YEAR
 1659      3.0   4.0   6.0   7.0  11.0  13.0  16.0  16.0  13.0  10.0   5.0   2.0     8.87
 1660      0.0   4.0   6.0   9.0  11.0  14.0  15.0  16.0  13.0  10.0   6.0   5.0     9.10

我知道我可以在电子表格中编辑和转换文件,将其保存为csv,然后使用csvRead进行读取,但是我想直接读取这种常见的文件。请记住,我不想显式读取此文件,而只是想读取此类文件。

我的尝试

1)strsubst-不起作用

我仅尝试这种文件(其中包含空格作为定界符):

fid=mopen("readblanks.txt","r"); // data file w/ multiple blanks and header
mat=mgetl(fid); // Read data as lines of strings in a matrix of strings
x=7; // Lines to skip for the header, normally prompted by the user
mat=mat(x+1:$,:); // Crop header lines

//// Following command just remove the first multiple blanks and I don't get this
//// to EOF as expected.
mat=strsubst(mat,"/[\s]+/", " ", "r"); // Replace multiple blanks w/ one blank

//// Convert string matrix to numerical matrix.

mclose(fid)

问题在////之后进行描述。我只想获取矩阵中的数字数据。我不需要标题。

2)重写裁剪后的标头文件并读回-可以,但是很糟糕

这是一种可行的方法,但是带有大型文件的操作非常浪费时间

fid1=mopen("readblanks.txt","r"); // data file w/ multiple blanks and header
mat=mgetl(fid1); // Read data as lines of strings in a matrix of strings
x=7; // Lines to skip for the header, normally prompted by the user
mat=mat(x+1:$,:); // Crop header lines
mclose(fid1);

fid2=mopen(TMPDIR + "/tmp.dat.txt","wt"); // temporary file
mfprintf(fid2, "%s\n", mat); // write header-purged temporary file
mat=fscanfMat(TMPDIR + "/tmp.dat.txt"); // read temporary file in matrix variable
mclose(fid2);
mdelete(TMPDIR + "/tmp.dat.txt"); // clean up
disp(mat)

您有更好的主意吗?这应该是常见的问题,但我找不到任何优雅的解决方案。

谢谢。

0 个答案:

没有答案