How to extract the following number from a text file?

4 ビュー (過去 30 日間)
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 23 日
コメント済み: Walter Roberson 2019 年 4 月 24 日
Dear memebers,
Can you please help me extract the following number hilighted in yellow from a text file into MATLAB?
The numbers will change each time but other characters will stay the same.
You can find the text file attached and that number will be at the end of the text.
Thank you!

採用された回答

Bob Thompson
Bob Thompson 2019 年 4 月 23 日
There are a couple of options how to do this. You can read the entire file in as strings, find the line you want, and regexp the numbers from the line, or you can choose to search through the entire thing by each line with fgetl, and look for a match, then extract the number based on the position of the numbers. Below are two examples, they will need some tweaking if you plan to use them.
% Regexp method
text = fileread('mypath\output_matlab.txt');
number = regexp(text,'Pile-head deflection\s+.\s+(\d.\d+) meters','tokens');
% fgetl method
fid = fopen('mypath\output_matlab.txt');
line = fgetl(fid);
count = 1;
while ~isnumeric(line)
if strcmp(line(1:9),'Pile-head')
number = str2num(line(30:40));
break
else
line = fgetl(fid);
count = count + 1;
end
end
  3 件のコメント
Bob Thompson
Bob Thompson 2019 年 4 月 24 日
Extracting from a cell is simple enough if you just specify a variable as the contents of the cell.
number = number{1};
Sometimes you may have to go a couple of levels deep, because regexp is silly about that. Just do {1}{1} if needed.
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 24 日
Yeah a couple of them worked, thanks!

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 4 月 23 日
編集済み: Walter Roberson 2019 年 4 月 24 日
filename = 'output_matlab.txt';
S = fileread(filename);
phd_str = regexp(S, '(?<=^Pile-head deflection\s+=\s+)\S+', 'match', 'lineanchors');
phd = str2double(phd_str);
This code will find any Pile-head deflection value that is in the file. If you are sure that there is only one in the file, then you can add the option 'once' to the regexp() call to speed up execution.
  2 件のコメント
Ahmad Fakih
Ahmad Fakih 2019 年 4 月 23 日
Thank you for your answer. Unfortunately the resulting phd is NaN (not a number) even when 'once' is used.
Walter Roberson
Walter Roberson 2019 年 4 月 24 日
I made a silly typing mistake when I copied the code in from what I had tested. I have fixed it now in what I posted.

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

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by