как получить номер строки, имеющей определенную строку в текстовом файле - Matlab - PullRequest
0 голосов
/ 28 декабря 2018

У меня есть текстовый файл, в котором много контента, и в этом файле много слов "include", и после этого я хочу получить данные из всех трех строк.

myFile.txt:"-включить:

-6,5 6,5

sin (x ^ 2)

diff

-включить

-5 5

cos (x ^ 4)

diff "

Как получить эти данные в массиве?

1 Ответ

0 голосов
/ 29 декабря 2018

Исходя из вашего примера (первое включает в себя : в конце, второе нет), вы можете использовать что-то вроде этого.

fID = fopen('myFile.txt'); % Open the file for reading
textString = textscan(fID, '%s', 'Delimiter', '\n'); % Read all lines into cells
fclose(fID); % Close the file for reading
textString = textString{1}; % Use just the contents on the first cell (each line inside will be one cell)
includeStart = find(contains(textString,'include'))+1; % Find all lines with the word include. Add +1 to get the line after
includeEnd = [includeStart(2:end)-2; length(textString)]; % Get the position of the last line before the next include (and add the last line in the file)
parsedText = cell(length(includeStart), 1); % Create a new cell to store the output
% Loop through all the includes and concatenate the text with strjoin
for it = 1:length(includeStart)
  parsedText{it} = strjoin(textString(includeStart(it):includeEnd(it)),'\n');
  % Display the output
  fprintf('Include block %d:\n', it);
  disp(parsedText{it});
end

В результате вы получите следующий вывод:

Include block 1:
-6.5 6.5
sin(x^2)
diff
Include block 2:
-5 5
cos(x^4)
diff

Вы можете настроить петлю в соответствии со своими потребностями.Если вам нужны номера строк, используйте переменные includeStart и includeEnd.

...