【发布时间】:2015-04-15 03:19:32
【问题描述】:
向您介绍我的问题的背景:我有两个包含基因信息的文件:
pos.bed 包含特定基因的位置,hg19-genes.txt 包含该物种的所有现有基因,并带有一些指示字符,例如基因的位置(开始和结束)、名称、符号等.
问题是在 pos 中,只显示了基因的位置,而不是它的名称/符号。我想通读这两个文件并比较每一行的开始和结束。如果有匹配,我想得到对应基因的符号。
我写了这个小python代码:
pos=open('C:/Users/Claire/Desktop/Arithmetics/pos.bed','r')
gen=open('C:/Users/Claire/Desktop/Arithmetics/hg19-genes.txt','r')
for row in pos:
row=row.split()
start=row[11]
end=row[12]
for row2 in gen:
row2=row2.split()
start2=row2[3]
end2=row2[4]
sym=row2[10]
if start==start2 and end==end2:
print sym
pos.close()
gen.close()
但这似乎只是逐行比较两个文件(例如文件 pos 中的第 2 行和文件 gen 中的第 2 行)。所以我尝试将 else 添加到 if 循环中,但我收到一条错误消息:
else:
gen.next()
StopIteration Traceback (most recent call last)
<ipython-input-9-a309fdca7035> in <module>()
14 print sym
15 else:
---> 16 gen.next()
17
18 pos.close()
StopIteration:
我知道可以通过以下方式比较 2 个文件的所有行,无论行的位置如何:
same = set(file1).intersection(file2)
但就我而言,我只想比较每一行的某些列,因为这些行在每个文件中都有不同的信息(开头和结尾除外)。是否有类似的方法来比较文件中的行,但仅限于某些指定的项目?
【问题讨论】:
标签: python file loops nested lines