I worked on a script that takes as input a multi-sequence .fasta
file and outputs the number of each aminoacid/sequence in a .tsv
format.
This is how a .fasta
file looks:
>sp|P21515|ACPH_ECOLI Acyl carrier protein phosphodiesterase OS=Escherichia coli (strain K12) OX=83333 GN=acpH PE=1 SV=2
MNFLAHLHLAHLAESSLSGNLLADFVRGNPEESFPPDVVAGIHMHRRIDVLTDNLPEVREAREWFRSETRRVAPITLDVMWDHFLSRHWSQLSPDFPLQEFVCYAREQVMTILPDSPPRFINLNNYLWSEQWLVRYRDMDFIQNVLNGMASRRPRLDALRDSWYDLDAHYDALETRFWQFYPRMMAQASRKAL
I know there are libraries which do the same thing, however, I had to write this script as a homework, without the help of BioPython
or other similar libraries.
My question is: how can I make this code more efficient?
import sys
import os
def readFasta( path ):
seq = { }
aCount = { }
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWYZX*-"
for fileName in path:
with open( fileName ) as file:
fastaLine = file.readlines( )
# sequence storage
for line in fastaLine:
if line[ 0 ] == ">" :
headerTitle = line.split( "|" )[ 1 ]
seq[ headerTitle ] = ""
else:
seq[ headerTitle ] += line.strip( )
# aminoacid count
for id in seq:
aCount[ id ] = { }
for sequence in seq[ id ]:
if sequence not in alphabet:
print( "Check your sequence! Character: " + str(sequence) + " from sequence: " + id )
for letter in alphabet:
aCount[ id ][ letter ] = 0
# count aminoacid occurence/sequence
for name in seq:
for char in seq[ name ]:
if char in aCount[ name ]:
aCount[ name ][ char ] += 1
# write to .csv file
outFile = open( "output.csv" , "w" )
outFile.write( "Name" + '\t' )
header = ""
for letter in alphabet:
header += letter + '\t'
outFile.write( header + "Total" )
outFile.write( '\n' )
for name in aCount:
entry = ""
counter = 0
for letter in aCount[ name ]:
entry += str(aCount[ name ][ letter ]).strip( ) + '\t'
counter += aCount[ name ][ letter ]
outFile.write( name + '\t' + entry + '\t' + str( counter ) )
outFile.write( '\n' )
# files to list
entries = os.listdir( path )
# filter for .fasta/.fa files
new_list = [ ]
for entry in entries:
if ".fasta" in entry:
new_list.append( entry )
elif ".fa" in entry:
new_list.append( entry )
# execute func
readFasta( new_list )
numpy.histogram
, I imaginepandas
/counter
/seaborn
(either by themselves or in any combination) would work too. \$\endgroup\$