2016-10-02 41 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 Ÿ空行(我認爲),但我不知道如何分割,並保存爲一個更小的文本文件:

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

相關問題