hey, thanks to all of them who helps me in learning this language,
again there is one text file
file 1.txt

>sp|P81928[/B]|140U_DROME

67 198 Tim17 8.9e-19 No_clan

>sp|P20905|5HT1R_DROME

179 507 7tm_1 1.1e-97 CL0192

>sp|P28285|5HT2A_DROME

243 805 7tm_1 3.2e-73 CL0192

>sp|P28286|5HT2B_DROME

107 588 7tm_1 7.2e-82 CL0192


* here the number represents the start and ending of subsequence which has to be extracted.

the next file is sequence file2.txt

>sp|P81928|140U_DROME RPII140-upstream gene protein OS=Drosophila melanogaster GN=140up PE=2 SV=2
MNFLWKGRRFLIAGILPTFEGAADEIVDKENKTYKAFLASKPPEETGLERLKQMFTIDEF
GSISSELNSVYQAGFLGFLIGAIYGGVTQSRVAYMNFMENNQATAFKSHFDAKKKLQDQF
TVNFAKGGFKWGWRVGLFTTSYFGIITCMSVYRGKSSIYEYLAAGSITGSLYKVSLGLRG
MAAGGIIGGFLGGVAGVTSLLLMKASGTSMEEVRYWQYKWRLDRDENIQQAFKKLTEDEN
PELFKAHDEKTSEHVSLDTIK
>sp|P20905|5HT1R_DROME 5-hydroxytryptamine receptor 1 OS=Drosophila melanogaster GN=5-HT7 PE=2 SV=1
MALSGQDWRRHQSHRQHRNHRTQGNHQKLISTATLTLFVLFLSSWIAYAAGKATVPAPLV
EGETESATSQDFNSSSAFLGAIASASSTGSGSGSGSGSGSGSGSGSYGLASMNSSPIAIV
SYQGITSSNLGDSNTTLVPLSDTPLLLEEFAAGEFVLPPLTSIFVSIVLLIVILGTVVGN
VLVCIAVCMVRKLRRPCNYLLVSLALSDLCVALLVMPMALLYEVLEKWNFGPLLCDIWVS
FDVLCCTASILNLCAISVDRYLAITKPLEYGVKRTPRRMMLCVGIVWLAAACISLPPLLI
LGNEHEDEEGQPICTVCQNFAYQIYATLGSFYIPLSVMLFVYYQIFRAARRIVLEEKRAQ
THLQQALNGTGSPSAPQAPPLGHTELASSGNGQRHSSVGNTSLTYSTCGGLSSGGGALAG
HGSGGGVSGSTGLLGSPHHKKLRFQLAKEKKASTTLGIIMSAFTVCWLPFFILALIRPFE
TMHVPASLSSLFLWLGYANSLLNPIIYATLNRDFRKPFQEILYFRCSSLNTMMRENYYQD
QYGEPPSQRVMLGDERHGARESFL
>sp|P28285|5HT2A_DROME 5-hydroxytryptamine receptor 2A OS=Drosophila melanogaster GN=5-HT1A PE=2 SV=2
MAHETSFNDALDYIYIANSMNDRAFLIAEPHPEQPNVDGQDQDDAELEELDDMAVTDDGQ
LEDTNNNNNSKRYYSSGKRRADFIGSLALKPPPTDVNTTTTTAGSPLATAALAAAAASAS
VAAAAARITAKAAHRALTTKQDATSSPASSPALQLIDMDNNYTNVAVGLGAMLLNDTLLL
EGNDSSLFGEMLANRSGQLDLINGTGGLNVTTSKVAEDDFTQLLRMAVTSVLLGLMILVT
IIGNVFVIAAIILERNLQNVANYLVASLAVADLFVACLVMPLGAVYEISQGWILGPELCD
IWTSCDVLCCTASILHLVAIAVDRYWAVTNIDYIHSRTSNRVFMMIFCVWTAAVIVSLAP
QFGWKDPDYLQRIEQQKCMVSQDVSYQVFATCCTFYVPLLVILALYWKIYQTARKRIHRR
RPRPVDAAVNNNQPDGGAATDTKLHRLRLRLGRFSTAKSKTGSAVGVSGPASGGRALGLV
DGNSTNTVNTVEDTEFSSSNVDSKSRAGVEAPSTSGNQIATVSHLVALAKQQGKSTAKSS
AAVNGMAPSGRQEDDGQRPEHGEQEDREELEDQDEQVGPQPTTATSATTAAGTNESEDQC
KANGVEVLEDPQLQQQLEQVQQLQKSVKSGGGGGASTSNATTITSISALSPQTPTSQGVG
IAAAAAGPMTAKTSTLTSCNQSHPLCGTANESPSTPEPRSRQPTTPQQQPHQQAHQQQQQ
QQQLSSIANPMQKVNKRKETLEAKRERKAAKTLAIITGAFVVCWLPFFVMALTMPLCAAC
QISDSVASLFLWLGYFNSTLNPVIYTIFSPEFRQAFKRILFGGHRPVHYRSGKL


i want to extract the subsequence from this sequences with respect to the proteins id

Dani AI

Generated

Two files are involved: one lists protein identifiers with start/end coordinates, the other is a FASTA file with the full sequences. Common failures come from header mismatches, line-wrapped FASTA lines, stray formatting (HTML tags in the ID lines), and—most important—indexing convention (0‑based vs 1‑based). already flagged the base question; asked for example output. The snippet below implements a robust, practical workflow that (1) cleans ID tokens, (2) builds a header->sequence map from the FASTA, (3) matches each range line to a FASTA header using a few heuristics, and (4) extracts slices with a selectable base (default = 1, i.e. 1‑based inclusive, which is most common in biology).

import re

def parse_ranges(path):
    entries = []
    cur_id = None
    with open(path) as fh:
        for raw in fh:
            line = raw.strip()
            if not line:
                continue
            if line.startswith('>'):
                tok = line.lstrip('>').split()[0]
                tok = re.sub(r'\[/?\w+\]', '', tok)    # strip stray tags
                cur_id = tok
            else:
                nums = re.findall(r'\d+', line)
                if len(nums) >= 2 and cur_id:
                    entries.append((cur_id, int(nums[0]), int(nums[1])))
    return entries

def read_fasta(path):
    seqs = {}
    hdr = None
    with open(path) as fh:
        for raw in fh:
            line = raw.rstrip()
            if not line: continue
            if line.startswith('>'):
                hdr = line.lstrip('>')
                seqs[hdr] = []
            else:
                seqs[hdr].append(line.strip())
    return {h: ''.join(parts) for h, parts in seqs.items()}

def match_header(seqs, id_token):
    for h in seqs:
        if h.startswith(id_token): return h
    for h in seqs:
        if id_token in h: return h
    if '|' in id_token:
        acc = id_token.split('|')[1]
        for h in seqs:
            if acc in h: return h
    return None

def extract_all(file1, file2, base=1):
    ranges = parse_ranges(file1)
    seqs = read_fasta(file2)
    out = []
    for idt, s, e in ranges:
        hdr = match_header(seqs, idt)
        if not hdr:
            print('no match for', idt); continue
        seq = seqs[hdr]
        if base == 1:
            s0 = s - 1; e0 = e
        else:
            s0 = s; e0 = e + 1
        s0 = max(0, s0); e0 = min(len(seq), e0)
        if s0 >= e0:
            print('invalid range for', idt, s, e); continue
        subseq = seq[s0:e0]
        out.append((hdr, s, e, subseq))
    return out

Output in FASTA (header annotated with original header and coords) is straightforward to write from the returned list. Troubleshooting notes: if many “no match” messages, print the set of FASTA headers and the parsed IDs to inspect mismatches; to decide the correct base, compare a known range to the sequence length (1‑based uses start=1 for the first residue); when coordinates exceed sequence length either clip with a warning or skip the entry. This approach handles multi-line FASTA and small formatting glitches while keeping extraction deterministic.

Recommended Answers

All 6 Replies

I see you are working with Drosophila genetics.
I'm not sure what you are trying to do.. can you explain it further?

wow that's some huge geek cred for knowing what that is.

Anyhow i don't exactly know what you want either so yeah.

For example that first line of first file looks different format (bold finishing tag before but no starting tag), otherwise, is it so that yo want to pick identifier between > and | psoition 1:9, (>sp|P20905| > id = sp|P20905) and when it is found take start and end indexes of two lines down of start and end index (0 or 1 based?)

Something like this for file1:

inp=open('file1.txt').read()

sep='>'
data= []
while sep:
    part,sep, inp = inp.partition(sep)
    if sep and part: data.append(part.strip().split('\n\n'))

idend = len('sp|P81928')-1
info = [( id[:idend],)+tuple(loc.split(' ',2)[:2])
        for id,loc in data if id.startswith('s')
         ]
print info
info = [(a, int(b), int (c)) for a,b,c in info]
print info

no it not like that sorry ,

i just want that from given sequence of lengh 400 , i have two cut the sequence ranging from one index to another index

If those where not right ids and indexes, I am afraid I can not help you.

wow that's some huge geek cred for knowing what that is.

Anyhow i don't exactly know what you want either so yeah.

Heh, I'm great at Biology (got first place in a state competition), so Drosophila melanogaster is very familiar to me. It's a fruitfly. I've helped raise them before.

Anyways, OP, can you provide us with some kind of desired output, so that we know exactly what you want?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.