2017-01-31 99 views
1

我有2个文件,查找ID坐标

1) A B  2) A,chr1,startA,endA 
    C D   B,chr1,startB,endB 
    B A   C,chr1,startC,endC 
       D,chr1,startD,endD 

我的期望输出,

A chr1 startA endA B chr1 startB endB 
C chr1 startC endC D chr1 startD endD 
B chr1 startB endB A chr1 startA endA 

我尝试让我的CHR,开始和结束的第一个ID,但我不知道如何关联并附加第二个ID。

f1=open('input1','r') 
f2=open('input2','r') 
output = open('out.txt','w') 
dictA= dict() 
for line1 in f1: 
    listA = line1.strip('\n').split('\t') 
    dictA[listA[0]] = listA 
for line1 in f2: 
    new_list=line1.rstrip('\r\n').split(',') 
    query=new_list[0] 
    chrom=new_list[1] 
    start=new_list[2] 
    end=new_list[3] 
    if query in dictA: 
     listA = dictA[query] 
     output.write(str(listA[0])+'\t'+str(listA[1])+'\t'+chrom+'\t'+start+'\t'+end+'\n') 
output.close() 
+0

这看起来有点像床形式;除了什么是'A','B'等? –

+0

基因ID's..我只是为了简单而写了AB – user3224522

+0

那么不要在染色体数量前添加基因ID,他们应该以姓名的形式出现,参见官方扩展的BED格式说明:https://genome.ucsc.edu/ FAQ/FAQformat#format1 –

回答

3

根据您的期望输出,我认为您可能会对此略有落后。现在看来似乎会更有意义的文件的内容存储在字典中,然后使用第一个文件的内容来查找字典中的数据,像这样

import io 

f1 = io.StringIO('A\tB\nC\tD\nB\tA\n') 
f2 = io.StringIO('A,chr1,startA,endA\r\nB,chr1,startB,endB\r\nC,chr2,startC,endC\r\nD,chr1,startD,endD') 

dictA = dict() 
for line in f2: 
    temp = line.strip().split(',') 
    dictA[temp[0]] = temp[1:] 

for line in f1: 
    id1, id2 = line.strip().split('\t') 
    print('\t'.join([id1] + dictA.get(id1, []) + [id2] + dictA.get(id2, []))) 

运行此结果

A chr1 startA endA B chr1 startB endB 
C chr2 startC endC D chr1 startD endD 
B chr1 startB endB A chr1 startA endA 

如果我认为我有file1.txt与内容

A B 
C D 
B A 

file2.txt与内容

A,chr1,startA,endA 
B,chr1,startB,endB 
C,chr1,startC,endC 
D,chr1,startD,endD 

然后我可以使用文件的读写方法来生成输出

f1 = open('file1.txt', 'r') 
f2 = open('file2.txt', 'r') 
output_file = 'output.txt' 

dictA = dict() 
for line in f2: 
    temp = line.strip().split(',') 
    dictA[temp[0]] = temp[1:] 
with open(output_file, 'w') as fp: 
    for line in f1: 
     id1, id2 = line.strip().split('\t') 
     fp.write('\t'.join([id1] + dictA.get(id1, []) + [id2] + dictA.get(id2, [])) + '\n') 
+0

谢谢你..但你可以使用文件打开和文件写入,bcos我的文件很大..这种格式根本不舒服... – user3224522

+0

我们在这里说话有多大?我们可以将文件2的内容存储在RAM中吗? – JCVanHamme

+0

不是那么大,但仍然是50k行..在第二个文件中我有10行,我只是缩短它在这里,所以文件变得相当庞大 – user3224522