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!