从NCBI 上下载 gbff 文件并得到 CDS 信息

最近入门学习生信,面临的一个问题就是如何下载和预处理海量的基因组数据,尤其是 NCBI 上的 gbff 基因组注释文件,网络上翻了很久也找到对新手比较友好的代码,索性自己写了一段~

要处理的有两个问题,在此分别讨论:

一. 如何下载指定的文件(压缩包)且压缩包不损坏?

在此参考 NCBI 官方指南:Genomes Download FAQ (nih.gov)

个人之前是使用 wget 下载,常常出现压缩包损坏的情况,换了 rsync 没有再出现过该问题。

抓取文件的后缀(可以更换):

- genomic.gbff.gz

- protein.faa.gz

网站地址(为啥我是用 https 而不是一步到位使用 rsync 或者 ftp?因为 https 我还可以直接进入该网页看看情况):

https://ftp.ncbi.nlm.nih.gov/refseq/release/archaea/

https://ftp.ncbi.nlm.nih.gov/refseq/release/bacteria/

# 安装/导入 os、re、request 包
# 终端操作: pip install requests
import os
import re
import requests

def load_url_context(type ,url):
    # 从网页中提取指定文件目录
    request = requests.get(url)
    raw_list = re.compile(r'<a.*?>(.*?)</a>').finditer(request.text.strip())
    file_name = "_".join([type,"context.txt"])
    with open(file_name, "w") as f:
        for i in raw_list:
            x = i.group(1)
            if x.endswith("genomic.gbff.gz") or x.endswith("protein.faa.gz"):
                file_https = ''.join([url,x])
                # 使用 rsync 开头
                file_ftp = file_https.replace("https","rsync")
                #print(file_ftp)
                f.write(file_ftp)
                f.write('\n')
        f.close()    

if __name__ == "__main__":
    archaea_url = "https://ftp.ncbi.nlm.nih.gov/refseq/release/archaea/"
    bacteria_url = "https://ftp.ncbi.nlm.nih.gov/refseq/release/bacteria/"
    load_url_context("archaea", archaea_url)
    load_url_context("bacteria", bacteria_url)

上面的代码最后生成文件下载路径,再写一个小脚本开始下载数据 

#!/bin/bash

while read line
do 
    rsync --copy-links --recursive --times --verbose $line bacteria/
done < archaea_context.txt

二. 是如何从注释文件中摘取自己想要的 CDS 注释信息

在上述网站上下载得到的数据是非常大的,尤其是细菌的基因组数据,但是有很多的注释信息我们用不到的,所以需要进一步操作精简一下内容。

在此我使用了 Biopython,用于 gbff 文件的导入,详情可以查看以下连接。

中文版:第5章 序列输入和输出 — Biopython-cn 0.1 文档

官网:Introduction to SeqIO · Biopython

本文我主要是想得到以下信息
 

Locus_tag

ORFStart..ORFStop

Strand

OrganismID

ContigID

Accession

KQY27_RS09175167785:168877-Methanobrevibacter sp. TMH8 k121_54413-GCF_020148105.1NZ_JAHLZE010000038.1WP_224426279.1
import os
# 提前下载 Biopython 包
from Bio import SeqIO

# 搜索 gbff 文件,返回 gbff 文件路径
def GbffContext(path, types):
    file_path  = path + types
    files_path = os.path.abspath(file_path)
    all_files = os.listdir(files_path)
    context = []
    for file in all_files:
        if file.endswith("gbff"):
            gbff_file_path = file_path + '/' + file
            context.append(gbff_file_path)

    return context



#产生 cds.pty 文件
def CdsCoordinate(path, type):
    record_iterator = SeqIO.parse(path, 'genbank')
    cds_file = '_'.join([type,"cds.pty"])

    with open(cds_file,'a') as f:
        try:
            while(True):
                record = next(record_iterator)
                t = record.features
                for t_cds in t:
                    # cds 注释中必然含有 protein_id 的 key
                    if t_cds.qualifiers.__contains__('protein_id'):
                        f.write(str(t_cds.qualifiers["locus_tag"])[2:-2])# locus_tag, [2:-2]为了去掉括号和引号,下文同理
                        f.write('\t')

                        f.write(str(t_cds.location)[1:-4]) # ORFStart..ORFStop
                        f.write('\t')

                        f.write(str(t_cds.location)[-2])# Strand
                        f.write('\t')

                        f.write(record.description.split(',')[0])
                        f.write('-')
                        f.write(str(record.dbxrefs[-1])[9:]) # OrganismID
                        f.write('\t')

                        f.write(record.id)# ContigID
                        f.write('\t')
                        
                        f.write(str(t_cds.qualifiers["protein_id"])[2:-2])# Accession number
                        f.write("\n")
        except StopIteration as e:
            print("已经完成", path, "CDS内容的搜索")
    f.close()


# 输入参数
if __name__ == "__main__":
    path = 'your_path'
    type = 'archaea/ bacteria'

    gbff_context = GbffContext(path, type)
    for gbff in gbff_context:  
        print(gbff)
        CdsCoordinate(gbff, type)

总结

虽然代码效率很慢,but it works.继续苦逼的生信学习~

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用BioPython库来从NCBI下载基因序列,下面是一个示例代码:from Bio import Entrez# Email address Entrez.email = "example@example.com"# Search for the gene handle = Entrez.esearch(db="nucleotide", term="gene_name") record = Entrez.read(handle)# Download the gene handle = Entrez.efetch(db="nucleotide", id=record["IdList"], rettype="fasta", retmode="text") gene_sequence = handle.read()print(gene_sequence) ### 回答2: 要利用PythonNCBI下载基因序列,可以使用biopython库来实现。Biopython是一个专门用于生物信息学的Python库,提供了众多工具和函数来处理基因、蛋白质及其他生物信息的分析和操作。 下面是一个示例代码,演示如何从NCBI下载基因序列: ```python from Bio import SeqIO from Bio import Entrez # 设置NCBI邮箱 Entrez.email = "your_email@example.com" # 查询指定基因 gene_query = "human[Orgn] AND BRCA1[Gene]" handle = Entrez.esearch(db="nucleotide", term=gene_query, retmode="xml") record = Entrez.read(handle) handle.close() # 获取查询结果中的基因序列 gene_id = record["IdList"][0] handle = Entrez.efetch(db="nucleotide", id=gene_id, rettype="fasta", retmode="text") gene_seq = SeqIO.read(handle, "fasta") handle.close() # 打印基因序列 print("Gene ID:", gene_id) print("Gene Description:", gene_seq.description) print("Gene Sequence:") print(gene_seq.seq) ``` 在这个示例代码中,首先需要设置自己的NCBI邮箱(将"your_email@example.com"替换为你的邮箱地址),这样可以方便地与NCBI服务器进行通信。 接下来,通过`Entrez.esearch()`函数来搜索指定的基因。这里以人类的BRCA1基因作为示例,查询条件为"human[Orgn] AND BRCA1[Gene]",即只搜索人类中的BRCA1基因。 然后,可以通过`Entrez.efetch()`函数来根据查询结果中的基因ID获取基因序列信息。设置`rettype`为"fasta"表示以FASTA格式返回基因序列。使用`SeqIO.read()`函数来解析FASTA文件,并将序列保存在`gene_seq`变量中。 最后,打印基因序列的相关信息,包括基因ID、描述以及序列本身。 以上代码仅为简单示例,实际中还可以根据需要进行更复杂的查询和操作。 ### 回答3: 要从NCBI下载基因序列,可以使用Biopython库中的Entrez模块。以下是一个用Python代码示例,用于从NCBI下载一个基因序列: ```python from Bio import Entrez, SeqIO # 设置NCBI邮箱 Entrez.email = 'your_email@example.com' # 设置搜索的关键词和数据库 search_term = 'KRAS[Gene Name]' database = 'nucleotide' # 搜索并获取符合条件的序列的ID search_handle = Entrez.esearch(db=database, term=search_term) search_result = Entrez.read(search_handle) search_handle.close() id_list = search_result['IdList'] # 从ID列表中下载序列 download_handle = Entrez.efetch(db=database, id=id_list[0], rettype='fasta', retmode='text') seq_record = SeqIO.read(download_handle, 'fasta') download_handle.close() # 打印基因序列的描述和序列信息 print('Description:', seq_record.description) print('Sequence:', seq_record.seq) ``` 要运行上述代码,首先需要安装Biopython库,可以使用`pip install biopython`命令进行安装。 在代码示例中,我们首先设置了NCBI邮箱,这是为了提高请求的速度和限制。然后,我们设置了要搜索的关键词和数据库,本例中我们搜索了基因名为KRAS的序列,使用了nucleotide数据库。 接下来,我们使用`Entrez.esearch()`函数搜索符合条件的序列的ID,并使用`Entrez.efetch()`函数根据ID下载序列。最后,我们使用`SeqIO.read()`函数读取下载的序列,并使用`description`和`seq`属性打印序列的描述和序列信息。 请注意,在使用上述代码之前,请确保替换`your_email@example.com`为你自己的邮箱地址,并根据你要下载的特定基因的要求修改`search_term`的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值