Last active
January 14, 2016 21:14
-
-
Save kescobo/49ab9f4b08d8a2691a40 to your computer and use it in GitHub Desktop.
Python definitions to take genbank file containing multiple genomes and dividing them into fasta protein files, one file per genome. For Stackoverflow question http://stackoverflow.com/posts/34777323/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from operator import itemgetter | |
from itertools import groupby | |
def gbk_to_faa(some_genbank): | |
source = None | |
for record in SeqIO.parse(some_genbank, 'gb'): | |
if source: | |
if record.annotations['source'] != source: | |
out_file.close() | |
source = sub(r'\W+', "_", sub(r'\W$', "", record.annotations['source'])) | |
out_file = open("{}.faa".format(source), "a+") | |
write_all_record(out_file, record) | |
else: | |
write_all_record(out_file, record) | |
else: | |
source = sub(r'\W+', "_", sub(r'\W$', "", record.annotations['source'])) | |
out_file = open("{}.faa".format(source), "a+") | |
write_all_record(out_file, record) | |
out_file.close() | |
def write_all_record(file_handle, gbk_record): | |
for feature in gbk_record.features: | |
if feature.type == "CDS": | |
tag = feature.qualifiers['locus_tag'][0] | |
seq = feature.qualifiers['translation'][0] | |
fasta(file_handle, tag, seq) | |
def fasta(file_handle, id, seq): | |
file_handle.write(">{}\n{}\n".format(id, seq)) | |
def from_stack(some_genbank): | |
for name, records in groupby(SeqIO.parse(some_genbank, 'gb'), lambda record:record.annotations['source']): | |
with open(name + ".faa", "w+") as outf: | |
for record in records: | |
write_all_record(outf, record) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment