gpt4 book ai didi

Python编程

转载 作者:太空宇宙 更新时间:2023-11-03 19:35:31 26 4
gpt4 key购买 nike

我的作业要求进行一个函数调用 readFasta,它接受一个参数:包含一个或多个序列的 fasta 格式文件 (fn) 的名称。该函数应该读取文件并返回一个字典,其中键是 fasta header ,值是文件 fn 转换为字符串的相应序列。确保字典中的序列中不包含任何换行符或其他空白字符。

例如,如果 afile.fa 看起来像:

>one
atctac
>two
gggaccttgg
>three
gacattac

然后 a.readFasta(f) 返回:

[‘one’ : ‘atctac’,
‘two’ : ‘gggaccttgg’,
‘three’: ‘gacattac’]

如果尝试编写一些代码,但由于我完全是编程新手,所以它对我来说效果不太好。大家可以帮帮我吗。太感谢了。这是我的代码:

import gzip

def readFasta(fn):
if fn.endswith('.gz'):
fh = gzip.gzipfile(fn)
else:
fh = open(fn,'r')

d = {}

while 1:
line = fh.readline()

if not line:
fh.close()
break

vals = line.rstrip().split('\t')
number = vals[0]
sequence = vals[1]

if d.has_key(number):
lst = d[number]

if gene not in lst:
# this test may not be necessary
lst.append(sequence)
else:
d[number] = [sequence]

return d

这是我在 afile.txt 中得到的内容

one atctac

two gggaccttgg

three gacattac

最佳答案

你的帖子有点令人困惑。我假设你希望它返回一个字典。在这种情况下,您可以将其写为 {'one': 'actg', 'two': 'aaccttgg' }。如果你正确地呈现了文件格式,那么这个函数应该可以解决问题。

import gzip

def read_fasta(filename):
with gzip.open(filename) as f:
return dict(line.split() for line in f)

关于Python编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com