5

可能重复:
从 matlab 中的文本文件中查找特定数据

我已经使用以下代码打开了标题为“gos.txt”的文本文件:

s={}; 
fid = fopen('gos.txt'); 
tline = fgetl(fid); 
while ischar(tline) 
   s=[s;tline]; 
   tline = fgetl(fid); 
end

我得到的结果如下:s =

'[Term]'    
'id: GO:0008150'
'name: biological_process'
'namespace: biological_process'
'alt_id: GO:0000004'
'alt_id: GO:0007582'
[1x243 char]
[1x445 char]
'subset: goslim_aspergillus'
'subset: goslim_candida'
'subset: goslim_yeast'
'subset: gosubset_prok'
'synonym: "biological process" EXACT []'
'synonym: "biological process unknown" NARROW []'
'synonym: "physiological process" EXACT []'
'xref: Wikipedia:Biological_process'
'[Term]'    
'id: GO:0016740'
'name: transferase activity'
'namespace: molecular_function'
[1x326 char]
'subset: goslim_aspergillus'
'subset: goslim_candida'
'subset: goslim_metagenomics'
'subset: goslim_pir'
'subset: goslim_plant'
'subset: gosubset_prok'
'xref: EC:2'
'xref: Reactome:REACT_25050 "Molybdenum ion transfer onto molybdopterin, Homo sapiens"'
'//is_a: GO:0003674 ! molecular_function'
'is_a: GO:0008150 ! molecular_function (added by Zaid, To be Removed Later)'
'//relationship: part_of GO:0008150 ! biological_process'
'[Term]'    
'id: GO:0016787'
'name: hydrolase activity'
'namespace: molecular_function'
[1x186 char]
'subset: goslim_aspergillus'
'subset: goslim_candida'
'subset: goslim_metagenomics'
'subset: goslim_plant'
'subset: gosubset_prok'
'xref: EC:3'
'//is_a: GO:0003674 ! molecular_function'
'is_a: GO:0016740 ! molecular_function (added by Zaid, to be removed later)'
'relationship: part_of GO:0008150 ! biological_process'
'[Term]'    
'id: GO:0006810'
'name: transport'
'namespace: biological_process'
'alt_id: GO:0015457'
'alt_id: GO:0015460'
[1x255 char]
'subset: goslim_aspergillus'
'subset: goslim_candida'
'synonym: "small molecule transport" NARROW []'
'synonym: "solute:solute exchange" NARROW []'
'synonym: "transport accessory protein activity" RELATED [GOC:mah]'
'is_a: GO:0016787 ! biological_process'
'relationship: part_of GO:0008150 ! biological_process'
.
.
.
.    

之后的步骤是如何获取某个字符并将其放入向量中。例如:我想将所有包含 'id: GO:*******' 的行放入向量中,我也是想要获得 'is_a: GO:*******' 到一个向量,请注意我不想在同一行中之后的字符。

4

2 回答 2

6

您可以在这里轻松使用regexp- 它适用于单元格:

matching_lines = s{~cellfun('isempty', regexp(s, '^id: GO'))}

ans =

 id: GO:0008150

ans =

 id: GO:0016740

提取所有以 . 开头的行id: GO。单独调用会为您提供 0/1的cellfun向量,其中 1 表示其中的字符串s与您的查询匹配。

类似的行查找包含is_a: GO:. 也可以使用 . 从字符串中删除不必要的字符regexp

可以使用以下'tokens'参数提取部分字符串regexp

tok = regexp(s, '^id: (GO.*)', 'tokens');
idx = ~cellfun('isempty', tok);
v   = cellfun(@(x)x{1}, {tok{idx}});
sprintf('%s ', v{:})

ans =

 GO:0008150 GO:0016740 
于 2012-10-23T10:05:04.150 回答
1

假设您只想在一行的开头找到东西,这很简单:

found=[]
for i=1:length(s)
    temp = s{i};
    if strcmp('id: GO:',temp(1:min(7,end));
        found = [found i];
    end
end

现在发现包含一个向量,其中包含以 id 开头的字符串的所有位置:GO:

我目前无法在 Matlab 中尝试,但这应该是正确的。

于 2012-10-23T09:52:28.630 回答