如何读取文本文件,提取level行的时间与对应数值至数组?
Got it, let's tackle this problem step by step. I’ve dealt with similar log parsing tasks in MATLAB before, and the issue with textscan is that it’s built for files where every line follows an identical structure—your file has a mix of regular entries and specific "level" lines, so regex is the way to go here. It lets us target exactly the lines we need, no matter where they show up.
Step 1: Read the Entire File First
First, we’ll pull the whole file into a single string. This makes it easier to scan for patterns across the entire content:
file_path = 'your_log_file.txt'; % Replace with your actual file name file_content = fileread(file_path);
Step 2: Use Regular Expressions to Extract Target Data
We’ll write a regex pattern that matches entries with "level XXX", capturing both the timestamp and the level number. The pattern accounts for both short timestamps (like 00:32.283) and longer ones (like 01:40:40.698):
% Regex pattern to capture timestamp and level value pattern = '(\d{2}(?::\d{2}){1,2}\.\d{3}) ID:\d+ level (\d+)'; % Extract all matching pairs as tokenized groups matches = regexp(file_content, pattern, 'tokens');
Let’s break down the pattern:
(\d{2}(?::\d{2}){1,2}\.\d{3}): Captures the timestamp—matches 2 digits, followed by 1 or 2 sets of:2 digits, then a decimal and 3 digits (covers bothMM:SS.sssandHH:mm:ss.SSSformats).ID:\d+ level: Matches the fixed middle part (works even if the ID number isn’t 4, just in case).(\d+): Captures the numeric level value.
Step 3: Convert Matches to Usable Arrays
Now we’ll split the captured tokens into separate arrays for timestamps and level values. We’ll also convert timestamps to seconds (super useful for plotting):
% Initialize arrays time_strings = cell(length(matches), 1); level_values = zeros(length(matches), 1); time_seconds = zeros(length(matches), 1); % Populate arrays from matches for i = 1:length(matches) % Extract timestamp string and level number time_strings{i} = matches{i}{1}; level_values(i) = str2double(matches{i}{2}); % Convert timestamp to total seconds for plotting timestamp = datetime(time_strings{i}, 'InputFormat', 'HH:mm:ss.SSS'); time_seconds(i) = seconds(timestamp - datetime('00:00:00', 'InputFormat', 'HH:mm:ss')); end
Alternative: Split Records First (For Debugging)
If you prefer a more explicit approach (great for checking each entry), you can split the file into individual log records first, then filter for "level" entries:
% Split the file into individual records (each starts with a timestamp) records = regexp(file_content, '(?=\d{2}(?::\d{2}){1,2}\.\d{3})', 'split'); records = records(~cellfun(@isempty, records)); % Remove empty entries % Initialize arrays time_strings = {}; level_values = []; % Loop through records to find "level" entries for rec = records if contains(rec, 'level') % Extract timestamp from the start of the record time_match = regexp(rec, '^\d{2}(?::\d{2}){1,2}\.\d{3}', 'match'); % Extract level number level_match = regexp(rec, 'level (\d+)', 'tokens'); % Only add if both values are found if ~isempty(time_match) && ~isempty(level_match) time_strings{end+1} = time_match{1}; level_values(end+1) = str2double(level_match{1}{1}); end end end
Testing with Your Sample Data
For the sample content you provided, both methods will extract:
- Time array:
["00:32.283", "00:32.205", "01:40:40.698"] - Level array:
[790, 640, 500]
And thetime_secondsarray will convert those timestamps to numeric values (like32.283,32.205,6040.698) which are ready for plotting.
内容的提问来源于stack exchange,提问作者António Silva

