I have a dataset with FASTA formatted sequencing, basically like this:
>pc284
ATCGCGACTCGAC
>pc293
ACCCGACCTCAGC
I want to take to use each tag as a key in the dictionary, and store the gene as a value.
This is the code I have, but really isn't doing anything:
import re
fileData = open('d.fasta', 'r')
myDict = dict()
for line in fileData:
match = re.search('(\>)(\w+)(\r)(\w+)', line)
if match:
gene = match.group(3)
myDict[gene[0]] = gene[1]
print myDict
\r
is not a valid character class, I think you meant to use\s
instead. You can reduce the groups if you don't use them either.But most of all, you need to extract your groups correctly:
By creating only two capturing groups, we can more simply extract those two with
.groups()
and directly assign them to two variables,tag
andgene
.However, reading up on the FASTA format seems to indicate this is a multi-line format with the tag on one line, the gene data on multiple lines after that. In that case your
\r
was meant to match the newline. This won't work as you read the file one line at a time.It would be much simpler to read that format without regular expressions like so:
This reads the file line by line, detecting tags based on the starting
>
character, then reads multiple lines of gene information collecting it into your dictionary under the most-recently read tag.Note the
rU
mode; we open the file using python's universal newlines mode, to handle whatever newline convention was used to create the file.Last but not least; take a look at the BioPy project; their
Bio.SeqIO
module handles FASTA plus many other formats perfectly.dont use a regex for this ...
Two errors I see:
Your regex is probably wrong. It's unlikely your FASTA input actually contains a bare carriage return (
\r
), so your regex won't match anything. Hence theif match:
test is always false, so nothing happens.Further, when processing each match: You are adding the first character of the
gene
(which is whitespace) as a key and the second character as the value.You probably meant to use groups 2 and 4 respectively:
Unless your file is too big to fit in memory (which I guess it is not), the whole thing is as simple as