2017-06-16 131 views
0

我有一个非常大的文本文件,里面有一个格式如下:如何动态添加前缀到文本文件中的行?

gene1 gene2

gene3

gene4

gene5

gene6

gene7 gene8

gene9

...

我想这个文件是这样的格式:

gene1 gene2

gene1 gene3

gene1 gene4

gene1 gene5

gene1 gene6

gene7 gene8

gene7 gene9

...

基因1,基因2,等等。有一些不,可以有不同的长度空间的字母组合..示例文件低于

https://drive.google.com/open?id=0B6u8fZadKIp2aEVIUTJ6NzlJVlk

可有人PLE是否指向正确的方向?

+0

请更明确的关于你想实现当你有2个基因多行..什么你想保持第一行的基因在眼前每一行还是你想继续重复的新基因?看到我对这个问题所做的修改,我理解正确吗? –

+0

谷歌驱动器中的文件只有256 kb,不能调用这个大文件。它只是整个文件的一部分吗? – Gelliant

回答

2
% getting the text and the first word 
text_in_file = fileread('oldfle.txt'); 
first_word = regexp(text_in_file, '\S*', 'match','once'); 

% generating the new string 
str = regexprep(text_in_file,'[\n\r]+',['\n\n' first_word ' ']); 
% writing to the file 
fid = fopen('newfile.txt', 'wt');fprintf(fid, str);fclose(fid); 

这里是一个修改后的代码,将处理与2个基因的许多行的情况。它重置计数并开始在单基因行前插入新的基因名称。那是你想要的吗?

% getting the text 
text_in_file = fileread('oldfile.txt'); 
% splitting into rows 
rows = regexp(text_in_file,'\n','split'); 
% number of genes in the rows 
A = cellfun(@(x) numel(regexp(x, '\t')), rows); 
% row indices with two genes 
two_word_rows = find(A==2); 
% first genes 
first_words = cellfun(@(x) regexp(x, '\S+', 'match', 'once'), rows(two_word_rows), 'UniformOutput' , false); 

% modifying the rows 
for i=setdiff(1:numel(rows), two_word_rows) % exclude the two gene rows 
    last_idx = find(two_word_rows<i,1,'last'); % which word to add? 
    rows{i} = sprintf('%s\t%s', char(first_words(last_idx)), rows{i}); 
end 

% writing to the file 
fid = fopen('newfile.txt', 'wt'); 
fprintf(fid, '%s', rows{:}); 
fclose(fid); 

请不要仅仅复制和粘贴代码。尝试通过它,阅读注释并查看使用函数的文档。

+0

我试过你的代码!但你知道,正如我所说的文本是非常大的,有很多情况下,当行有2列,下一行只有一列我共享文件PLZ检查它 –

+0

兄弟,我的文件有一个基因和它的邻居,ilts喜欢一个基因有很多邻居,因为有这么多基因在行中有2个基因意味着这个基因1是第一个邻居是基因2,然后列出下一行中的其他邻居 –

+0

第二个代码有一个错误:未定义的函数'strsplit '输入参数 类型'char'。 Neighbors_network中的错误(第13行) rows = strsplit(text_in_file,'\ n'); –

1

此代码导入所有32491基因名称,然后将它们写入新文件。

oldfile='file.txt'; 
newfile='file2.txt'; 
fclose all; 
fid=fopen(oldfile,'r'); 
genes={}; 
l=fgetl(fid); 
while ~isnumeric(l) 
    l = regexp(l, '\W', 'split'); 
    l = l(~cellfun(@isempty,l)); 
    if ~isempty(l) 
     genes(end+1:end+numel(l))=l; 
    end 
    l=fgetl(fid); 
end 
fclose(fid); 

fid=fopen(newfile,'wt'); 
for ct = 2:numel(genes) 
    fprintf(fid,'%s %s\n',genes{1},genes{ct}); 
end 
fclose(fid); 

输出:

TGM1 HIST1H4C 
TGM1 HIST1H4B 
TGM1 HIST1H4A 
TGM1 TGM3 
TGM1 HIST1H4G 
TGM1 HIST1H4F 
TGM1 HIST1H4E 
TGM1 HIST1H4D 
TGM1 HIST1H4K 
TGM1 HIST1H4J 
(etc.) 
+1

Vahe Tsjitoyan的方法更加优雅。了解他在regexprep中所做的工作,并对其进行改进,使其适用于您的文件。 '\ s +'匹配空格。所以如果你把'[\ n \ r] +'改成'[\ n \ r \ s] +'它可能已经有效了。 – Gelliant

+0

我认为OP需要澄清他想要实现什么时,有多个行有2个基因... –

+0

Gelliant我改变它,但不工作 –

相关问题