私はまだ初心者ですので、明らかな答えで申し訳ありませんが、乱雑なコードは残念ですが、10万本のファイルがあります。私は特定のウィンドウフレームテクニックを使ってファイルをスライドさせるので、すべてのウィンドウがそこにあることを確認する必要があります。しかし、私の入力ファイルの中には特定の行がありませんので、Pythonでこれらの行と必要な情報を追加してファイルを完成させるコードを書き込もうとしました。これは、コードは次のようになります。TSVファイルに欠落しているシーケンス行を記入する方法
#!/usr/bin/env python
outfile = open ("missing_test.txt", "w")
with open("add_missing.txt", "r") as file:
last_line = 0 #This is where it starts for bin 1
lines = []
header_line = next(file)
outfile.write(header_line)
CHROM = 'BABA_1'
for line in file: #go through every line to check its existence and rewrite to new file
nums = line.split("\t")
num1 = nums[0] #no integer because this is a string: name individual
num2 = int(nums[1]) #integer for window
num3 = int(nums[2]) #integer for coverage (here always 10000 to met treshold)
num4 = int(nums[3]) #integer for SNP count
if num1 == CHROM: #
while num2 != last_line + 10000:
#A line is missing, so a new line is added with 0 SNPs:
NUM2 = last_line + 10000 # New window, the one that was missing
NUM4 = 0 #0 SNPs found
#lines.append((num1, NUM2, num3, NUM4))
OUTLINE = "%s\t%s\t%s\t%s" % (num1, NUM2, num3, NUM4) #write new line to outfile
outfile.write(OUTLINE + "\n")
last_line += 10000
lines.append((num1,num2,num3,num4))
last_line += 10000 #also add 10000 here otherwise the while loop makes no sense
outline = "%s\t%s\t%s\t%s" % (num1, num2, num3, num4)
outfile.write(outline + "\n") #write all existing lines to outfile
else:
CHROM = num1
last_line = 0
outfile.close()
だから、これは最初の「CHROM」の最初のウィンドウ限り、完全に正常に動作し必ずしもそうではありませんこれは、0に等しいです。そして、後者の場合、ループは無限になります。これは、例えばどのような入力のためのものであり、所望の出力は次のようになります。
入力:
indiv window coverage SNP
BABA_1 20000 10000 7
BABA_1 30000 10000 1
BABA_1 50000 10000 2
BABA_1 60000 10000 3
BABA_1 80000 10000 1
BABA_10 20000 10000 1
BABA_10 30000 10000 16
BABA_10 80000 10000 9
所望の出力:
indiv window coverage SNP
BABA_1 10000 10000 0
BABA_1 20000 10000 7
BABA_1 30000 10000 1
BABA_1 40000 10000 0
BABA_1 50000 10000 2
BABA_1 60000 10000 3
BABA_1 70000 10000 0
BABA_1 80000 10000 1
BABA_10 10000 10000 0
BABA_10 20000 10000 1
BABA_10 30000 10000 16
BABA_10 40000 10000 0
BABA_10 50000 10000 0
BABA_10 60000 10000 0
BABA_10 70000 10000 0
BABA_10 80000 10000 9
私は私のこのwhileループを得るのに苦労して答えを探してきました無限に進むことなく作業していますが、私は真剣に私の欠陥を見ません。誰かが私がこれを解決する方法についてのヒントを持っていますか?
ご協力いただきありがとうございます。
「CHROM」が0に等しくない場合は、基本的に 'while'ループを終了します。これは正しいですか? –
実際にはCHROMは実際には文字列であり、いったんその文字列が変更されると、やり直したい – visse226
大文字と小文字を区別する必要があります。 'num1'と' NUM1'は同じではありません。 –