因此,我在从更大的(>GB)文本文件中提取文本时遇到了问题。该文件的结构如下:
>header1
hereComesTextWithNewlineAtPosition_80
hereComesTextWithNewlineAtPosition_80
hereComesTextWithNewlineAtPosition_80
andEnds
>header2
hereComesTextWithNewlineAtPosition_80
hereComesTextWithNewlineAtPosAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAlineAtPosition_80
MaybeAnotherTargetBBBBBBBBBBBrestText
andEndsSomewhereHere
现在,我有了这样的信息:在带有header2
的条目中,我需要将文本从位置X提取到位置Y(本例中的A),从1开始,作为标题下方行中的第一个字母。
但是:这些位置不考虑换行符。基本上,当它从1到95的时候,它实际上是指从1到80的字母,以及下一行的15个字母。
我的第一个解决方案是使用file.read(X-1)跳过前面不需要的部分,然后使用file.read(Y-X)来获得我想要的部分,但是当它延伸到换行符时,我会得到很少的字符。
除了read()之外,还有其他python函数解决这个问题的方法吗?我考虑用空字符串替换所有换行符,但是文件可能相当大(数百万行)。
我还试图通过将extractLength // 80
作为增加的长度来解释换行符,但是在例如eg的例子中,这是有问题的。在95个字符,它是2-80-3超过3行,我实际上需要2个额外的位置,但95 // 80
是1。
更新:
我修改了代码以使用Biopython:
for s in SeqIO.parse(sys.argv[2], "fasta"):
#foundClusters stores the information for substrings I want extracted
currentCluster = foundClusters.get(s.id)
if(currentCluster is not None):
for i in range(len(currentCluster)):
outputFile.write(">"+s.id+"|cluster"+str(i)+"\n")
flanking = 25
start = currentCluster[i][0]
end = currentCluster[i][1]
left = currentCluster[i][2]
if(start - flanking < 0):
start = 0
else:
start = start - flanking
if(end + flanking > end + left):
end = end + left
else:
end = end + flanking
#for debugging only
print(currentCluster)
print(start)
print(end)
outputFile.write(s.seq[start, end+1])
但我得到了以下错误:
[[1, 55, 2782]]
0
80
Traceback (most recent call last):
File "findClaClusters.py", line 92, in <module>
outputFile.write(s.seq[start, end+1])
File "/usr/local/lib/python3.4/dist-packages/Bio/Seq.py", line 236, in __getitem__
return Seq(self._data[index], self.alphabet)
TypeError: string indices must be integers
UPDATE2:
将outputFile.write(s.seq[start, end+1])
更改为:
outRecord = SeqRecord(s.seq[start: end+1], id=s.id+"|cluster"+str(i), description="Repeat-Cluster")
SeqIO.write(outRecord, outputFile, "fasta")
及其工作:)
发布于 2015-10-26 14:53:02
from Bio import SeqIO
X = 66
Y = 130
for s in in SeqIO.parse("test.fst", "fasta"):
if "header2" == s.id:
print s.seq[X: Y+1]
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Biopython让我们解析fasta文件并轻松访问它的id、描述和序列。然后,您就有了一个Seq
对象,您可以方便地操作它,而无需对所有内容进行重新编码(如反向补码等)。
https://stackoverflow.com/questions/33347847
复制相似问题