How to read a specific value next to a text in a text file?
5 ビュー (過去 30 日間)
古いコメントを表示
Hi everyone,
I am using MATLAB to read a specific file and I need to extract information. The format is as follows
Value (any number) - / text here (A)
Value (any number) - / text here (B)
I would like to know how to extract all the value for the "- / text here (B)". Thanks for your help in advance.
4 件のコメント
回答 (2 件)
Oguz Kaan Hancioglu
2023 年 2 月 17 日
I understand your data format is text-based as you want to read or write both numbers and strings. If all elements of the data are separated using special delimiters, you can use the readtable command. Than you can find your txt B using string commands and reach the value.
clc; clear;
fileName = 'New Text Document.txt'
T = readtable(fileName,'Format','auto');
disp(T);
bIndex = find(strcmp(string(T.Var2),'2pi')==1);
disp(double(T.Var1(bIndex)))
readtable supports many file formats including .xls, .xml, .docx, .html.
https://www.mathworks.com/help/matlab/ref/readtable.html
0 件のコメント
Stephen23
2023 年 2 月 17 日
raw = strtrim(readlines('Txt.txt'));
idx = strcmp(raw,'')|strcmpi(raw,'Zone,');
raw(idx) = [];
% split the values and keys:
spl = regexp(raw,'[,;]\s*!-\s*','split','once');
spl = vertcat(spl{:});
% convert to table:
idy = startsWith(spl(:,1),'Zone');
idz = 1+cumsum(idy);
zab = ["";spl(idy,1)];
spl(:,3) = zab(idz);
tbl = array2table(spl(~idy&idz>1,:), 'VariableNames',{'Value','Key','Name'})
% unstack to a more useful arrangement:
tbl = unstack(tbl,'Value','Key', 'VariableNamingRule','preserve');
tbl = convertvars(tbl,@(s)all(~isnan(double(s))),'double')
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Environment and Settings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!