使用Biopython从gff文件提取gene的位置以及gene的id,再从fna文件提取gene序列

这段代码展示了如何利用Biopython的GFF和SeqIO模块从GFF文件中获取基因位置和ID,然后从FNA文件中提取相应的基因序列。由于Biopython的顺序问题,代码使用了字典嵌套列表来保存信息,并处理了位置偏移。最后,提取的基因序列被写入到.fasta文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Biopython从gff文件提取gene的位置以及gene的id,再从fna文件提取gene序列

需要注意的是 Biopython存储到parse里面的并不是和文件的 染色体的顺序一致,在这里对字典嵌套列表,保存基因的位置以及其他信息,biopython读取的序列切片是从0开始的,这里它读取的基因的位置整体偏移1位

在这里插入图片描述
头部几个和NcBI里面的对比一下
在这里插入图片描述
对比一下尾部几个碱基

from Bio import SeqIO
from BCBio import GFF
import re

def get_geneLocation_geneId(in_file,gene_len):
    """
        本函数主要应用于从gff文件提取gene的location以及gene的id
        in_file 为 输入的 gff文件
        gene_len 为 需要提取的基因长度
    """
    in_handle = open(in_file)
    gene_information =dict()
    for rec in GFF.parse(in_handle):
        j=0
        i=0
        while j<len(rec.features):
            if rec.features[j].type=='region':
                tem = str(rec.features[j].id.split(':')[0])
                gene_information[tem]=[]
            if rec.features[j].type=='gene':               
                gene_location_t=[int(s) for s in re.findall(r'-?\d+\.?\d*', str(rec.features[j].location))]
                if gene_location_t[1]-gene_location_t[0] < gene_len :
                    gene_information[tem].append([gene_location_t[0],gene_location_t[1],\
                                                 str(rec.features[j].qualifiers['ID']),\
                                             str(rec.features[j].qualifiers['gene_biotype']),\
                                             str(rec.features[j].location)])
                    i+=1
            j+=1
    in_handle.close()
    return gene_information

def get_gene_gff_fna(file_path_gff,file_path_fna,save_path='./',gene_len=10000):#"GCF_904848185.1_fAcaLat1.1_genomic.gbff"
    '''
        本函数主要是用来从fna文件里面提取gene序列的
    '''
    return_gene=[]
    gene_information= get_geneLocation_geneId(file_path_gff,gene_len)
    with open(save_path+'.fasta','w',encoding='utf-8') as f:
        for seq_record in SeqIO.parse(file_path_fna, "fasta"):
            tem = str(seq_record.description.split()[0])
            for j in range(len(gene_information[tem])):
                return_gene.append(str(seq_record.seq[gene_information[tem][j]

下面的代码是添加的文件操作,把提取到的gene保存到*.fasta文件里面,,,具体的保存格式上图对比图有

from Bio import SeqIO
from BCBio import GFF
import re
import os
def get_geneLocation_geneId(in_file,gene_len):
    """
        本函数主要应用于从gff文件提取gene的location以及gene的id
        in_file 为 输入的 gff文件
        gene_len 为 需要提取的基因长度
    """
    in_handle = open(in_file)
    gene_information =dict()
    for rec in GFF.parse(in_handle):
        j=0
        i=0
        while j<len(rec.features):
            if rec.features[j].type=='region':
                tem = str(rec.features[j].id.split(':')[0])
                gene_information[tem]=[]
            if rec.features[j].type=='gene':               
                gene_location_t=[int(s) for s in re.findall(r'-?\d+\.?\d*', str(rec.features[j].location))]
                if gene_location_t[1]-gene_location_t[0] < gene_len :
                    gene_information[tem].append([gene_location_t[0],gene_location_t[1],\
                                                 str(rec.features[j].qualifiers['ID']),\
                                             str(rec.features[j].qualifiers['gene_biotype']),\
                                             str(rec.features[j].location)])
                    i+=1
            j+=1
    in_handle.close()
    return gene_information

def get_gene_gff_fna(file_path_gff,file_path_fna,save_path='./',gene_len=10000):#"GCF_904848185.1_fAcaLat1.1_genomic.gbff"
    '''
        本函数主要是用来从fna文件里面提取gene序列的
    '''
    return_gene=[]
    gene_information= get_geneLocation_geneId(file_path_gff,gene_len)
    i=0
    with open(save_path+'.fasta','w',encoding='utf-8') as f:
        c=0
        ge=0
        for seq_record in SeqIO.parse(file_path_fna, "fasta"):
            tem = str(seq_record.description.split()[0])
            for j in range(len(gene_information[tem])):
                f.write('>')
                f.write(seq_record.description.split()[0])
                f.write(' ')
                f.write(str(seq_record.description.split()[1]))
                f.write(' ')
                f.write(str(seq_record.description.split()[2]))
                f.write(' ')
                f.write('chr')
                for aa in seq_record.description.split()[5:-4]:
                    f.write(str(aa))
                    f.write(' ')
                f.write(gene_information[tem][j][2])
                f.write(' ')
                f.write(gene_information[tem][j][3])
                f.write(' ')
                f.write(gene_information[tem][j][4])
                f.write('\n')
                return_gene.append(str(seq_record.seq[gene_information[tem][j][0]:gene_information[tem][j][1]]))
                n=0
                for m in return_gene[-1]:
                    if n<80:
                        f.write(m)
                        n+=1
                    else:
                        f.write('\n')
                        n=0
                f.write('\n')
                c+=1
            print(c)
            i+=1
    print('extra gene over')
    return return_gene,gene_information
<think>好的,用户的问题是从GFF文件根据微卫星位点的位置区间批量提取基因ID。首先,我需要回忆GFF文件的结构。GFF文件通常包含染色体、来源、类型、起始位置、结束位置、得分、链、阶段和属性等信息。用户需要根据微卫星的区间(即特定的染色体、起始和结束位置)来匹配基因的区间,并提取对应的基因ID。接下来,我需要确定如何实现这一点。常见的方法包括使用命令行工具如awk或bedtools,或者编写Python脚本处理。用户可能需要批量处理,因此效率也很重要。考虑到GFF文件可能很大,使用高效的工具如bedtools会更好,因为它专门处理基因组区间,并且能够快速进行区间交集查询。然后,具体步骤方面,首先需要准备微卫星的区间文件,可能是BED格式,包含染色体、起始、结束等信息。然后使用bedtools intersect命令来找到与GFF文件基因区间重叠的部分。不过,GFF文件中的基因条目通常在第3列为“gene”,所以可能需要先提取这些行,转换成BED格式,再进行交集操作。另外,需要注意GFF文件的坐标是否是基于1的,而BED文件是基于0的,所以在转换时要调整起始位置。例如,GFF的起始位置需要减1才能转换为BED格式的起始。还有,提取基因ID时,GFF的属性列(第9列)通常包含ID等信息,格式类似于“ID=gene:ENSG00000198712;Name=TP53;”,需要用正则表达式或其他方法解析出ID部分。 用户可能需要具体的代码示例,所以给出使用bedtools的命令行步骤,以及Python脚本的示例会比较全面。同时,提醒用户注意文件格式的差异和坐标转换的问题,避免错误。最后,考虑到用户可能不熟悉这些工具,提供相关的安装命令和简单说明也是有帮助的,比如如何安装bedtools,如何运行Python脚本等。此外,生成相关问题可以帮助用户进一步学习,比如如何处理其他类型的区间查询,或者使用其他工具如Biopython等。</think>### 解决方案 要从GFF文件根据微卫星位点的区间批量提取对应基因ID,需通过以下步骤实现: #### 1. **理解GFF文件结构** GFF文件每行包含9个字段,关键字段为: - `CHROM`:染色体名称(如chr1) - `START`:特征起始位置(1-based) - `END`:特征结束位置 - `ATTRIBUTES`:基因ID等元数据(如`ID=gene:ENSG0000012345`) #### 2. **构建微卫星区间文件** 将微卫星位点保存为BED格式文件(0-based坐标),格式为: ``` chr1 1000 2000 chr2 5000 6000 ``` #### 3. **使用工具进行区间匹配** **方法一:bedtools(推荐)** ```bash # 安装bedtools sudo apt-get install bedtools # 将GFF文件转换为BED格式(保留基因区间和ID) awk '$3 == "gene" {print $1 "\t" $4-1 "\t" $5 "\t" $9}' input.gff > genes.bed # 执行区间交集查询 bedtools intersect -a microsatellites.bed -b genes.bed -wa -wb > overlaps.txt ``` **方法二:Python脚本** ```python from BCBio import GFF def extract_genes(gff_file, bed_file): # 读取微卫星区间 with open(bed_file) as f: regions = [line.strip().split('\t') for line in f] # 解析GFF文件 gene_ids = [] with open(gff_file) as f: for rec in GFF.parse(f): for feat in rec.features: if feat.type == "gene": # 检查是否与微卫星区间重叠 for chrom, start, end in regions: if (rec.id == chrom and int(start) <= feat.location.end and int(end) >= feat.location.start): gene_id = feat.qualifiers.get("ID", ["unknown"])[0] gene_ids.append(gene_id) return gene_ids ``` #### 4. **结果处理** 通过`overlaps.txt`或Python输出结果,可提取第7列的基因ID,例如: ``` chr1 999 2000 ID=gene:ENSG000001234 ``` ### 注意事项 - **坐标系统转换**:GFF使用1-based坐标,BED使用0-based,需在转换时调整起始位置[^1] - **性能优化**:对于大型文件建议使用bedtools,其时间复杂度为$O(n \log n)$ - **ID解析**:基因ID可能包含复杂结构(如`gene:ENSG000001234`),可用`sed 's/.*ID=//'`提取
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值