Read text file with multiple rows of fields

9 ビュー (過去 30 日間)
David K
David K 2019 年 11 月 22 日
コメント済み: Jeremy Hughes 2019 年 11 月 22 日
I am trying to read in a large text file with a challenging formatting. Instead of one long row of many fields, the file is broken into chunks with multiple rows of fields. Additionally, the headers repeat every so often and at an inconsistent rate. I've attached an example. I am trying to find a way to efficiently read in the data and organize it so that each field is a single array in a struct/cell/table/etc. The best I can think of is just to go line by line, knowing how many rows are in each block, and detect when I've encountered headers.

採用された回答

Jeremy Hughes
Jeremy Hughes 2019 年 11 月 22 日
The current best way I know how to do this is with TEXTSCAN.
fmt = "%s%s%s%s%*[^\r\n]%*[\r\n]%s%s%s%s"
fid = fopen('sampleFile.txt')
data = textscan(fid,fmt,1,'Delimiter','\t','HeaderLines',5) % will read two lines at a time.
data = textscan(fid,fmt,1,'Delimiter','\t') % after header
This is just a starting point, you'll have to do some work based on the results you're looking for in the file.
  2 件のコメント
David K
David K 2019 年 11 月 22 日
This is great, thank you! I didn't realize you could include line breaks like that. What is the purpose of the %*[^\r\n] in your formatSpec? Just to catch any extra characters at the end that might show up? I tried it without and it seemed to work fine.
Jeremy Hughes
Jeremy Hughes 2019 年 11 月 22 日
That's absolutly right. %*[^\r\n]%*[\r\n] skips up to the next instance of \r or \n, then skipping all the following \r or \n characters. It's a neat trick for consuming lines.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by