我有一个fasta文件(由> header和sequence行组成),如下所示:
myfasta
>S.sclerotiorum_Ch16_153_209
AACCCTAACCCTAACCCTTGATTGATTGATTGATTGATTGAT
TGATTGATGAAATTATAGTCTCCGTAAAGCAAATAAAGCATT
TAGTAAACGTTGAAGAGCTAGAAAAGCTTTAATACAAAAAGG
>S.sclerotiorum_Ch16_153_209
AACCCTAACCCTAACCCTTGATTGATTGATTGATTGATTGAT
TAGTAAACGTTGAAGAGCTAGAAAAGCTTTAATACAAAAAGG
>S.sclerotiorum_Ch14_442_1137
TGTCAATTCGATCTAGTATT
>S.sclerotiorum_Ch12_1831_180
AGAGCTAGAAAAGCTTTAAT
>S.sclerotiorum_Ch1_1831_180
AGAGCTAGAAAAGCTTTAATAGAGCTAGAAAAGCTTTAAT
AGAGCTAGAAAAGCTTTAATAGAGCTAGAAAAGCTTTAAT
我想按定义的顺序打印此文件(从Ch1到Ch16开始),并得到如下结果:
>S.sclerotiorum_Ch1_1831_180
AGAGCTAGAAAAGCTTTAATAGAGCTAGAAAAGCTTTAAT
AGAGCTAGAAAAGCTTTAATAGAGCTAGAAAAGCTTTAAT
>S.sclerotiorum_Ch12_1831_180
AGAGCTAGAAAAGCTTTAAT
>S.sclerotiorum_Ch14_442_1137
TGTCAATTCGATCTAGTATT
>S.sclerotiorum_Ch16_153_209
AACCCTAACCCTAACCCTTGATTGATTGATTGATTGATTGAT
TAGTAAACGTTGAAGAGCTAGAAAAGCTTTAATACAAAAAGG
>S.sclerotiorum_Ch16_153_209
AACCCTAACCCTAACCCTTGATTGATTGATTGATTGATTGAT
TGATTGATGAAATTATAGTCTCCGTAAAGCAAATAAAGCATT
TAGTAAACGTTGAAGAGCTAGAAAAGCTTTAATACAAAAAGG
我试图编写此代码,但是我的result.fasta
中的输入文件的顺序仍然与我相同。任何帮助将不胜感激修复我的代码。谢谢!
代码:python code.py myfasta.fasta >> result.fasta
#!/usr/bin/env python
import sys
import os
import pathlib
myfasta = sys.argv[1]
fasta = open(myfasta)
#types = ['S.sclerotiorum_Ch16_', 'S.sclerotiorum_Ch15_', 'S.sclerotiorum_Ch14_', 'S.sclerotiorum_Ch13_', 'S.sclerotiorum_Ch12_', 'S.sclerotiorum_Ch11_', 'S.sclerotiorum_Ch10_', 'S.sclerotiorum_Ch9_', 'S.sclerotiorum_Ch8_', 'S.sclerotiorum_Ch7_', 'S.sclerotiorum_Ch6_', 'S.sclerotiorum_Ch5_', 'S.sclerotiorum_Ch4_', 'S.sclerotiorum_Ch3_', 'S.sclerotiorum_Ch2_', 'S.sclerotiorum_Ch1_']
types = ['S.sclerotiorum_Ch1', 'S.sclerotiorum_Ch2', 'S.sclerotiorum_Ch3', 'S.sclerotiorum_Ch4', 'S.sclerotiorum_Ch5', 'S.sclerotiorum_Ch6', 'S.sclerotiorum_Ch7', 'S.sclerotiorum_Ch8', 'S.sclerotiorum_Ch9', 'S.sclerotiorum_Ch10', 'S.sclerotiorum_Ch11', 'S.sclerotiorum_Ch12', 'S.sclerotiorum_Ch13', 'S.sclerotiorum_Ch14', 'S.sclerotiorum_Ch15', 'S.sclerotiorum_Ch16']
for type in range(len(types)):
flag = False
fasta = open(myfasta)
for line in fasta:
if line.startswith('>') and types[type] in line:
flag = True
elif line.startswith('>'):
flag = False
if flag:
#grabbed = line.strip()
#newfasta.writelines(grabbed + "\n")
print(line.strip())
fasta.close
答案 0 :(得分:1)
您可以将re.findall
用于与某行匹配的模式,然后再匹配以非{>
字符开头的行,并在Ch
之后将数字分组,请使用{{1} }根据数字对匹配项进行排序,然后使用sorted
将排序后的子字符串重新连接回字符串:
str.join
给出您存储在import re
''.join(s for s, _ in sorted(re.findall(r'(.*_Ch(\d+)_.*\n(?:[^>].*\n)*)', f), key=lambda t: int(t[1])))
中的输入字符串(您应该先将整个文件读入此变量),这将返回:
f