Anyone here who uses Python for solving bioinformatics problems. This is the code I have written for counting the number of k-mers like monomers, dimers to hexamers from the fasta file. You just have to give the ncbi accession number for the fasta sequence and then it counts the number of k-mers. If you've time, please check the code as I think it's a bit long one and I have used try/except for solving IndexError. Your suggestions would be valuable. Thanks.
from Bio import Entrez
Entrez.email = '[email protected]'
monomers = list('ATGC')
dimers = []
for i in monomers:
for j in monomers:
dimers.append(i+j)
trimers = []
for i in monomers:
for j in monomers:
for k in monomers:
trimers.append(i+j+k)
tetramers = []
for i in monomers:
for j in monomers:
for k in monomers:
for l in monomers:
tetramers.append(i+j+k+l)
pentamers = []
for i in monomers:
for j in monomers:
for k in monomers:
for l in monomers:
for m in monomers:
pentamers.append(i+j+k+l+m)
hexamers = []
for i in monomers:
for j in monomers:
for k in monomers:
for l in monomers:
for m in monomers:
for n in monomers:
hexamers.append(i+j+k+l+m+n)
file = input('Enter the ncbi accession number: ')
handle = Entrez.efetch(db = 'nucleotide', id = file,rettype="fasta", retmode="text")
record = handle.read()
fasta_string = ''.join(record.split('\n')[1:])
k = int(input('Enter the value of k: '))
print('The sequence is',fasta_string)
fasta_list = []
if k == 1:
a = True
while a:
try:
for i in range(0,len(fasta_string),1):
fasta_list.append(fasta_string[i])
except:
break
a = False
for i in monomers:
print('count of' ,i, 'is' , fasta_list.count(i))
elif k == 2:
a = True
while a:
try:
for i in range(0,len(fasta_string),2):
fasta_list.append(fasta_string[i]+fasta_string[i+1])
except:
break
a = False
for i in dimers:
print('count of' ,i, 'is' , fasta_list.count(i))
elif k == 3:
a = True
while a:
try:
for i in range(0,len(fasta_string),3):
fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2])
except:
break
a = False
for i in trimers:
print('count of' ,i, 'is' , fasta_list.count(i))
elif k == 4:
a = True
while a:
try:
for i in range(0,len(fasta_string),4):
fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3])
except:
break
a = False
for i in tetramers:
print('count of' ,i, 'is' , fasta_list.count(i))
elif k == 5:
a = True
while a:
try:
for i in range(0,len(fasta_string),5):
fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3]+fasta_string[i+4])
except:
break
a = False
for i in pentamers:
print('count of' ,i, 'is' , fasta_list.count(i))
elif k == 6:
a = True
while a:
try:
for i in range(0,len(fasta_string),6):
fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3]+fasta_string[i+4]+fasta_string[i+5])
except:
break
a = False
for i in hexamers:
print('count of' ,i, 'is' , fasta_list.count(i))
Counting the number of k-mers like monomers, dimers to hexamers from the fasta file