Python 查找ID坐标
我有两个文件Python 查找ID坐标,python,bioinformatics,Python,Bioinformatics,我有两个文件 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
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
我的try给了我第一个ID的chr,开始和结束,但是我不知道如何关联和附加第二个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()
根据你想要的结果,我认为你可能在这方面有点落后。似乎将第二个文件的内容存储在字典中,然后使用第一个文件的内容在字典中查找数据更有意义,如下所示
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
A,chr1,startA,endA
B,chr1,startB,endB
C,chr1,startC,endC
D,chr1,startD,endD
和file2.txt
及其内容
A B
C D
B A
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')
这看起来有点像床的形式;除了但什么是‘A’、‘B’等?基因ID。我只是简单地写了一个B。不要在染色体编号之前添加基因ID,它们应该作为名称,请参见官方的扩展床格式规范:你确定在第二个文件中,每行的“键”完全符合该行的第一个字符,或者可能有其他字符?是的,但我不需要BED格式,我需要为我的每个ID获取起点和终点…谢谢..但是你可以使用文件打开和文件写入,bcos我的文件很大..这种格式一点也不舒服…我们在这里谈论的是多大?我们是否可以将文件2的内容存储在RAM中?不是很大,但仍有50k行..在第二个文件中,我有10行,我只是在这里缩短了它,因此该文件变得相当大,使用实际的FileSuper进行了编辑以解决问题,同时使其工作正常..谢谢!