Skip to main content
 首页 » 编程设计

python之解析 multi-fasta 文件以提取序列

2024年10月01日6EasonJim

我正在尝试用 python 编写一个脚本来解析一个大的 fasta 文件,我不想使用 biopython,因为我正在学习脚本。脚本需要将入藏号、序列长度、序列gc内容打印到控制台。我已经能够提取登录号,但无法提取序列,因为它们被读取为行,这使我无法计算序列长度和 gc 内容。

谁能帮帮我? 我试图将列表中的行分组,但随后在列表中创建了多个列表,我也不确定如何加入它们。

seq="" 
seqcount=0 
seqlen=0 
gc=0 
 
#prompt user for file name 
infile=input("Enter the name of your designated .fasta file: ") 
 
with open(infile, "r") as fasta: 
    print("\n") 
    print ("Accession Number \t Sequence Length \t GC content (%)") 
    for line in fasta: 
       line.strip() 
       if line[0]==">": 
           seqcount+=1 #counts number sequences in file 
           accession=line.split("|")[3] #extract accession 
           seq="" 
       else:  
           seq+=line[:-1] 
           seqlen=len(seq) 
           print(accession, "\t \t", seqlen) 
 
print("\n")            
print("There are a total of", seqcount, "sequences in this file.") 

请您参考如下方法:

你离正确的代码不远了:

seq="" 
seqcount=0 
 
#prompt user for file name 
infile=input("Enter the name of your designated .fasta file: ") 
 
def pct_gc(s): 
    gc = s.count('G') + s.count('C') + s.count('g') + s.count('c') 
    total = len(s) 
 
    return gc*100.0/total 
 
with open(infile, "r") as fasta: 
    print("\n") 
    print ("Accession Number\tSequence Length\tGC content (%)") 
    for line in fasta: 
        line = line.strip() 
        if line[0]==">": 
            if seq != "": 
                print("{}\t{}\t{}".format(accession, pct_gc(seq), len(seq))) 
 
            seqcount+=1 #counts number sequences in file 
            accession=line.split("|")[3] #extract accession 
            seq="" 
        else:  
            seq+=line[:-1] 
 
print("{}\t{}\t{}".format(accession, pct_gc(seq), len(seq))) 
print("\n")            
print("There are a total of " + str(seqcount) + " sequences in this file.") 

要寻找的东西:

  • 您不需要在每次迭代中都更新长度。最后计算一下。
  • str.strip() 不修改对象,而是返回一个剥离的对象
  • 您必须使用这样一个事实,即当您找到下一个序列并且该序列不为空时,您知道您阅读了一个完整的序列。在这一点上,您必须编写输出。
  • 最后一个序列没有被新的加入完成,所以你必须在循环之后的最后独立处理它。
  • 使用字符串格式或连接字符串。如果您只是将字符串和变量用逗号分隔,您将得到一个元组表示输出。