Python:一种用read()忽略/解释换行符的方法

2024-04-25 18:57:42 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,从较大的(>;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个字母。你知道吗

我的第一个解决办法是文件.read(X-1)跳过前面不需要的部分,然后文件.read(Y-X)来获取我想要的部分,但是当它延伸到换行时,我只提取了几个字符。你知道吗

有没有其他的python函数来解决这个问题?我想用空字符串替换所有的换行符,但是文件可能相当大(数百万行)。你知道吗

我还试图通过将extractLength // 80作为附加长度来解释换行符,但这在一些情况下是有问题的,例如当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

更新2:

更改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")

以及它的工作原理:)


Tags: 文件inidforif字母leftstart
1条回答
网友
1楼 · 发布于 2024-04-25 18:57:42

使用Biopython

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让您解析一个文件并轻松访问其id、描述和序列。然后就有了一个Seq对象,可以方便地对它进行操作,而无需重新编码所有内容(如反向补码等)。你知道吗

相关问题 更多 >