我试图用python编写一个程序,将符合特定条件的数据行从输入文件解析为一系列输出文件。在
这个程序读取一个输入文件,其中包含染色体上基因的起始和终止位置。对于这个输入文件的每一行,它逐行打开第二个输入文件,其中包含感兴趣染色体上已知snp的位置。如果SNP位于被迭代的基因的起始位置和终止位置之间,它将被复制到一个新的文件中。在
我的程序目前的问题是效率低下。对于每一个被分析的基因,程序从第一行开始读取SNP数据的输入文件,直到它到达一个SNP,该SNP位于比被迭代的基因的停止位置更大(即具有更高的位置号)的染色体位置。由于所有的基因和SNP数据都是按染色体位置排序的,如果我能以某种方式“告诉”我的程序从上次迭代中读取的最后一行开始读取SNP位置数据的输入文件,而不是从文件。在
有没有办法做这个Python?还是所有文件都必须从第一行读取?在
到目前为止我的代码如下。如有任何建议,将不胜感激。在
import sys
import fileinput
import shlex
geneCoordinates = open("Gene Coordinates.txt",'r')
geneCoordinates = list(geneCoordinates)
n = (len(geneCoordinates))
nSNPsPerGene=open("C:/Users/gwilymh/Desktop/Python/SNPsPerGene/nSNPs per gene.txt", 'a')
i=0
for i in range(i,n):
x=i
L=shlex.shlex(geneCoordinates[x],posix=True)
L.whitespace += ','
L.whitespace_split = True
L=list(L)
output=open((("C:/Users/gwilymh/Desktop/Python/SNPsPerGene/%s.txt")%(str(L[2]))), 'a')
geneStart=int(L[2])
geneStop=int(L[3])
for line in fileinput.input("SNPs.txt"):
if not fileinput.isfirstline():
nSNPs=0
SNP=shlex.shlex(line,posix=True)
SNP.whitespace += '\t'
SNP.whitespace_split = True
SNP=list(SNP)
SNPlocation=int(SNP[0])
if SNPlocation < geneStart:
continue
if SNPlocation >= geneStart:
if SNPlocation <= geneStop:
nSNPs=nSNPs+1
output.write(str(SNP))
output.write("\n")
else: break
nSNPsPerGene.write(("%s\t%s")%s(str(L[2]),nSNPs))
只需使用迭代器(在循环之外的范围内)来跟踪您在第二个文件中的位置。应该是这样的:
相关问题 更多 >
编程相关推荐