我有一個文本檔案,表格上方有標題行,表格下方是一個空行,然后是一個包含表格摘要統計資訊的表格。處理標題行很容易,因為大多數標準函式都有一個選項(即 readtable)。檔案的長度并不總是相同的。問題readtable在于頁腳表的列數少于主表,因此該函式無法讀取這些行并回傳錯誤。
這是我得到的錯誤readtable:
Error using readtable (line 216)
Reading failed at line 2285. All lines of a text file must have the same number of delimiters. Line 2285 has 0 delimiters, while preceding lines
have 24.
Note: readtable detected the following parameters:
'Delimiter', '\t', 'HeaderLines', 21, 'ReadVariableNames', true, 'Format', '%T%f%f%f%q%f%f%f%f%f%f%q%f%f%f%f%f%f%f%f%f%f%f%f%f'
這是我提出的替代解決方案:
dataStartRow = 23;
numRows = length(readmatrix(filePath, 'NumHeaderLines',0));
dataEndRow = numRows - 8;
opts = detectImportOptions(filePath);
opts.DataLines = [dataStartRow, dataEndRow];
dataTable = readtable(filePath, opts);
這有效,但我有另一個具有不同頁腳行數的檔案,我不知道如何在沒有頁腳行數硬編碼的情況下處理這個問題。
我已經考慮使用fgetl, 并逐行閱讀以確定何時停止添加到表格中,但這似乎效率很低。如何使用未知數量的表格行和未知數量的頁腳行匯入此表格?
uj5u.com熱心網友回復:
首先,不要斷定某些東西“看起來效率很低”,除非您已經對其進行了分析或計時,并發現它實際上對于您的要求來說太慢了。
但是,在這種情況下,您可以通過設定delimitedTextImportOptions 物件的此屬性來更改 MATLAB 在發生錯誤時采取的操作:
opts = detectImportOptions(filePath);
opts.ImportErrorRule = 'omitrow'; # ignore any lines that don't match the detected pattern
dataTable = readtable(filePath, opts);
如果您經常使用此代碼讀取新資料,我會考慮進行某種驗證dataTable以確保它與您的期望一致,以防萬一新檔案detectImportOptions由于某種原因導致給出不同的結果。例如,如果您知道列數及其格式應始終相同,則可以指定
opts.Format = '%T%f%f%f%q%f%f%f%f%f%f%q%f%f%f%f%f%f%f%f%f%f%f%f%f';
然后檢查結果表是否為空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/389988.html
