所以我有一個問題,從一個較大的(> GB)文本文件中提取文本。該文件的結構如下:Python:一種方法來忽略/考慮換行()
>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(YX)來獲得我想要的部分,但是當它延伸到換行符時得到幾個提取的字符。
有沒有辦法解決這個與另一個python函數比read()也許?我想過用空字符串替換所有換行符,但該文件可能相當大(數百萬行)。
我也嘗試通過將extractLength // 80
作爲附加長度來解釋換行符,但是在例如例如。的95個字符是2-80-3在3線其實我需要2個額外的位置,但95 // 80
爲1
UPDATE:
我修改代碼以使用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")
,其工作:)
爲什麼不使用Biopython? – jrjc
你應該提取哪些內容的規則並不完全清楚,或者你爲什麼不能逐行迭代文件。 – jonrsharpe
@jeanrjc我沒有使用biopython的經驗。你會如何使用它?至於爲什麼我不只是逐行迭代文件:我想要提取的文本是由開始和結束位置指定的,如我所說,跨越多行並開始/結束在一行的中間是可能的,但我沒有想要整個線路。 – voiDnyx