tags:

views:

73

answers:

4

I have a file that contains two sequences. I have a program that could read all sequences, combine them together, and display the length of both sequences together. Now I want to display the length individually. The two sequences are separated by the symbol >.

Example:

SEQ1 >ATGGGACTAGCAGT

SEQ2  >AGGATGATGAGTGA

Program:

#!usr/bin/python
import re
fh=open('clostp1.fa','r')
count=0
content=fh.readlines()
fh.close()
seq=''
patt=re.compile('>(.*?)')
for item in content:
    m=patt.match(item)
    if not m:
        s=item.replace('\n','')
        seq=seq+s
seq=seq.replace('\s','')       
print seq
print 'The length of the coding sequence of the bacillus' 
print len(seq)
+4  A: 
for line in open("clostp1.fa"):
    name, sequence = map(str.strip,line.split('>'))
    print "The length of %s is %s"%(name, len(sequence))
gnibbler
Actually I prefer this one to mine :P
mandel
it will works if each line have only one '>' ;)
They only have one '>' in the examples. If there can be more than one we need to be told what to do with those lines.
gnibbler
Use `line.split('>', 1)` if your sequence can contain `'>'` character.
Denis Otkidach
I think they look like dna or something, so probably not more than one '>' per line
gnibbler
+1  A: 

If I understood correctly, you want to print out each individual sequence followed by its length, right? I believe you just have a function to return the sequences and later do what ever yuo want with them.

#!usr/bin/python
import re

def get_content(file):
    """
    Returns a dict with the name of the seq and its value
    """
    result = {}
    for current_line in open(file):
        name, value = line.strip().split(">")
        result[name] = value
    return result

You get the dict and then print what ever you need to print.

mandel
A: 
for line in open("clostp1.fa"):
    name, _, seq = line.partition('>')
    name, seq = name.rstrip(), seq.rstrip()
    print("The length of {} is {}".format(name, len(seq)))

partition is more appropriate here then split. you need to rstrip each individual part, and formatting syntax will work in py3.1, use

print("The length of {0} is {1}".format(name, len(seq)))

to make it work in py2.6.

SilentGhost
doesn't partition return a 3-tuple?
gnibbler
oops, yes, thanks gnibbler
SilentGhost
A: 
import re
pattern = re.compile('(?P<seqname>\w*)\s*>\s*(?P<seqval>\w*)')
for item in open('clostp1.fa','r').readlines():
    m = pattern.match(item)
    if m:
       print "sequence name: %s - %s length" % (m.groupdict()['seqname'],len(m.groupdict()['seqval']))
you don't need to have .readlines() there, you can just iterate over the file. readlines() will read the whole file into memory at once which can be bad if the file is very big
gnibbler