Finding and Extracting Instances from a Text File

조회 수: 10 (최근 30일)
Nima
Nima 2020년 12월 15일
댓글: Nima 2020년 12월 16일
Hi All,
I have a large text file and I need to save all instances of string which comes after a key_name and are betwen specific characters.
For example, there are many instances of strings in the file - could be numebrs, characters, letters - with unknown length, but in the file they all appear after a known key_name phrase and are between known symbols. Example: key_name/':"/This_is_the_string"/
The format always repeat like this, and I want to search for like < key_name/':"/ > and then in an array store whatever comes after the searched phrase up to the next < "/ > character set. There is no space in the text file.
Thank you for your help
UPADTES:
A sample text file is attched. So, I'd like the Matlab script returns an array saying "answer" with three value:
answer = [abc def3ghi JK]
  댓글 수: 2
Matt Gaidica
Matt Gaidica 2020년 12월 16일
Can you attach a sample file? It will help cover all cases when someone tries to help.
Nima
Nima 2020년 12월 16일
Attached.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2020년 12월 16일
편집: Walter Roberson 2020년 12월 16일
Another approach is to use regexp with named tokens
S = fileread('sample_text.txt');
t = regexp(S, 'keyname/'':"(?<kn>[^"]*)', 'names')
This should return a struct array with field kn that holds one key each.
Subhadeep's use of regexp is fine for the exact task you laid out, but if you wanted to extend to the key names and corresponding value tag then named token approach is easier to extend.
  댓글 수: 1
Nima
Nima 2020년 12월 16일
Walter,
Thank you for your answer. Your script worked great. As I replied to the above answer from Subhadeep, his code did find all instances too but it took a few hours to capture, but the script you wrote did the job in less than 5 seconds. I would use this one.
Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Subhadeep Koley
Subhadeep Koley 2020년 12월 16일
Hi, the below code might help.
% Open the file
fid = fopen('sample_text.txt');
% Read the file by character
str = fread(fid, 'uint8=>char');
% Close the file
fclose(fid);
% Search <key_name/':"/> by regural expression matching
[~, endIdx] = regexpi(str', 'key_name/'':"/');
% Find values
result = "";
for ind = 1:length(endIdx)
temp = string(str(endIdx(ind):end)');
result(ind) = strtok(temp, '"/');
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2020년 12월 16일
regexp() with 'match' option would have cut out a lot of code. Also, regexp() can work on entire long character vectors, not restricted to line-by-line.
Nima
Nima 2020년 12월 16일
good points.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by