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!