Chatgpt比我强太多了。个人觉得只要你说的需求足够详细,他很快就能完成一个初学者抓耳挠腮写一下午的代码。
我想要用叶绿体的fasta数据练习构建进化树。需要很多近缘物种的fasta文件。其他文献已经列好了他们使用的genebank number。我就很懒,我就想坐享其成。
chatgpt写的第一个脚本是这样的。
#!usr/python
import os
import sys
from Bio import Entrez, SeqIO
Entrez.email = "******@gmail.com"
# 设置email地址,以便NCBI联系你
# 定义一个下载函数,接受一个genebank number作为参数
def download_gb(gb):
# 使用efetch下载fasta格式的文件
handle = Entrez.efetch(db="nucleotide", id=gb, rettype="fasta", retmode="text")
# 读取数据并关闭句柄
data = handle.read()
handle.close()
# 返回读取的数据
return data
# 如果没有提供文件名参数,则输出帮助信息并退出
if len(sys.argv) != 2:
print("Usage: python get_gff.py genebank_list_file")
sys.exit(1)
# 从命令行参数中获取文件名
input_file_name = sys.argv[1]
# 打开输入文件和输出文件
with open(input_file_name, "r") as input_file, open("fasta_list.txt", "w") as output_file:
# 逐行读取输入文件
for line in input_file:
# 去除换行符并下载相应的genebank number的fasta文件
gb = line.strip()
fasta = download_gb(gb)
# 将fasta文件保存为以genebank number命名的文件
output_file.write(gb + "\n")
with open(gb + ".fasta", "w") as fasta_file:
fasta_file.write(fasta)
print("Done!")
然后我发现使用还不是很‘’官方”,于是添加了我的需求。
这是ver1.0
#!/usr/bin/env python
"""
About: This script downloads FASTA files from NCBI for a list of GenBank IDs.
Usage: python getfasta.py genebank.list [out.list]
genebank.list: a text file containing GenBank IDs, one per line
out.list (optional): a text file to save the list of downloaded GenBank IDs and their corresponding species names
Note: This script uses the Entrez module from Biopython to retrieve FASTA sequences from NCBI. Please make sure you have Biopython installed.
"""
import sys
if len(sys.argv) < 2 or sys.argv[1] == '-h':
print(__doc__)
sys.exit()
import os
import sys
from Bio import Entrez
from Bio import SeqIO
def fetch_fasta(genebank_id):
# 定义email地址
Entrez.email = "**********@gmail.com"
# 使用efetch下载fasta格式的序列
handle = Entrez.efetch(db="nucleotide", id=genebank_id, rettype="fasta", retmode="text")
# 读取序列并返回
return handle.read()
if len(sys.argv) < 2:
print("Usage: python getfasta.py genebank.list [out.list]")
else:
# 获取输入文件名
input_file_name = sys.argv[1]
# 如果有输出文件名,则打开文件准备写入
if len(sys.argv) > 2:
output_file_name = sys.argv[2]
output_file = open(output_file_name, "w")
else:
output_file = None
# 打开输入文件
with open(input_file_name, "r") as input_file:
# 遍历每一行,获取genebank ID并下载对应fasta序列
for line in input_file:
genebank_id = line.strip()
try:
fasta = fetch_fasta(genebank_id)
except:
# 如果下载失败则跳过该行
print(f"Warning: {genebank_id} cannot be downloaded.")
continue
# 将fasta序列写入文件
fasta_file_name = genebank_id + ".fasta"
with open(fasta_file_name, "w") as fasta_file:
fasta_file.write(fasta)
# 如果有输出文件则写入对应关系
if output_file:
handle = Entrez.efetch(db="nucleotide", id=genebank_id, rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
organism = record.annotations["organism"]
output_file.write(f"{genebank_id}\t{organism}\n")
# 关闭输出文件
if output_file:
output_file.close()
# 输出完成信息
print("All done!")
这是两个小时的训练成果。主要的是对我的需求进行一步步的具现化。他生成代码的时间都很短。
更新:这个脚本没啥大用。
网友评论