2016-10-02 2 views
0

나는 다음과 같습니다 큰 텍스트 파일을 가지고 :MATLAB을 사용하여 큰 텍스트 파일을 모든 빈 줄에 작은 텍스트 파일로 분할하는 방법은 무엇입니까?

PMID- 123456123 
OWN - NLM 
DA - 20160930 

PMID- 27689094 
OWN - NLM 
VI - 2016 
DP - 2016 

PMID- 27688828 
OWN - NLM 
STAT- Publisher 
DA - 20160930 
LR - 20160930 

등등 ... 나는 모든 빈 줄에 따라 작은 텍스트 파일에 텍스트 파일을 분할하고 싶은 . 또한 PMID 번호에 해당하는 각각의 텍스트 파일의 이름을, 그래서 다음과 같습니다

파일 이름 '123456123.txt'가 포함

PMID- 123456123 
OWN - NLM 
DA - 20160930 

파일 이름 '27689094.txt'가 포함

PMID- 27689094 
OWN - NLM 
VI - 2016 
DP - 2016 

파일 이름 '27688828.txt는'포함

PMID- 27688828 
OWN - NLM 
STAT- Publisher 
DA - 20160930 
LR - 20160930 

이, 나는 IDENTIF하는 방법을 내 시도 알고있다 Y 빈 줄 (내 생각)하지만 난 분할 작은 텍스트 파일로 저장하는 방법을 알고하지 않습니다

fid = fopen(filename); 
text = fgets(fid); 
blankline = sprintf('\r\n'); 

while ischar(text) 
    if strcmp(blankline,str) 
     %split the text 
    else 
     %write the text to the smaller file 
    end 
end 

답변

2

당신은 전체 파일을 읽은 다음 빈 줄에 내용을 분할 regexp를 사용할 수 있습니다. 그런 다음 regexp을 다시 사용하여 각 그룹의 PMID를 추출한 다음 모든 조각을 반복하여 저장합니다. 이처럼 하나의 거대한 문자열로 파일을 처리하는 것은 fgets을 사용하여 파일을 한 장씩 읽는 것보다 훨씬 더 효과적 일 수 있습니다.

% Tell it what folder you want to put the files in 
outdir = '/my/folder'; 

% Read the initial file in all at once 
fid = fopen(filename, 'r'); 
data = fread(fid, '*char').'; 
fclose(fid); 

% Break it into pieces based upon empty lines 
pieces = regexp(data, '\n\s*\n', 'split'); 

% For each piece get the PMID 
pmids = regexp(pieces, '(?<=PMID-\s*)\d*', 'match', 'once'); 

% Now loop through and save each one 
for k = 1:numel(pieces) 
    % Use the PMID of this piece to construct a filename 
    filename = fullfile(outdir, [pmids{k}, '.txt']); 

    % Now write the piece to the file 
    fid = fopen(filename, 'w'); 
    fwrite(fid, pieces{k}); 
    fclose(fid); 
end 
+0

대단히 감사합니다. – tamkrit

관련 문제