首页 > 解决方案 > 字典从函数返回空

问题描述

我正在编写一个函数,该函数接收一个可能有多个序列的 fasta 文件,并返回一个字典,其中加入号作为键,全长标题作为值。当我运行该函数时,我得到了一个空字典,但是当我在函数之外运行相同的代码时,我得到了所需的字典。我认为这意味着函数中的某个地方我的字典被什么都覆盖了,因为如果它与我的正则表达式模式有关,那么代码也不会在函数之外工作,但我似乎无法找到字典的位置正在重置。我尝试做一些寻找解决方案的方法,但我发现相同问题的唯一问题有明显的问题(没有返回值或输入变量之一被覆盖)。

这是我的功能代码和输出(假设重新导入):

def getheader(file):
    '''
    compiles headers from a fasta file into a dictionary

    Parameters
    ----------
    file : file
        file that contains the sequences with headers and has not been read

    Returns
    -------
    dictionary with acc no as key and full header as value

    '''
    head_dict = {}

    for line in file:
        if line.startswith(">"):
            acc = re.search(">([^\s]+)", line).group(1)
            header = line.rstrip()
            head_dict[acc] = header
        
    return head_dict

file = open("seq1.txt", "r")
head_dict = getheader(file)
print(head_dict)

输出

{}

这是我在函数之外运行它时的输入/输出:

import re
file = open("seq1.txt", "r")
head_dict = {}

for line in file:
    if line.startswith(">"):
        key = re.search(">([^\s]+)", line).group(1)
        value = line.rstrip()
        head_dict[key] = value


print(head_dict)

输出

{'AF12345': '>AF12345 test sequence 1'}

其中 seq1.txt 是以下不带引号的文件,并且 txt 文件具有实际返回而不是“\n”,我只是不确定如何正确格式化它。

">AF12345 测试序列 1\nCGATATTCCCATGCGGTTTATTTATGCAAAACTGTGACGTTCGCTTGA"

以上是我的代码现在所在的位置。在此之前,我有一个函数可以创建两个字典并根据输入参数返回一个特定的字典。一本字典是入藏号和序列,另一本是我现在正在尝试创建的字典。返回第一本字典我没有任何问题。因此,我决定拆分该功能并为每个字典设置一个,尽管它看起来很重复。我也尝试将 移到head_dict[key] = value条件语句之外,并遇到了同样的问题。我尝试将变量名称从keytoacc和 from valueto 更改header,但仍然得到相同的结果(您可以在函数外部的示例中看到变量最初keyvalue)。我只是尝试将空字典作为参数,以便在函数外部对其进行初始化,但我仍然得到一个空字典返回。我不确定现在该尝试什么。提前致谢!

注意:我确信这可以通过另一个库更有效地解决,但这是针对一堂课的,教师非常反对使用其他库。我们必须先学会如何自己做。

编辑:现在我很沮丧。我重写了代码以添加创建输入文件,供人们用来运行我的代码并帮助我处理它,但它确实有效。很抱歉浪费了大家的时间。这是我重写的内容。如果您发现这与我在上面发布的内容之间存在差异,请告诉我。

import re
def getheader(file):
    '''
    compiles headers from a fasta file into a dictionary

    Parameters
    ----------
    file : file
        file that contains the sequences with headers and has not been read

    Returns
    -------
    dictionary with acc no as key and full header as value

    '''
    head_dict = {}
    
    for line in file:
        if line.startswith(">"):
            acc = re.search(">([^\s]+)", line).group(1)
            header = line.rstrip()
            head_dict[acc] = header
            
    return head_dict

file = open("bookishbubs_test1.txt", "w")
file.write(">AF12345 test sequence 1\nCGATATTCCCATGCGGTTTATTTATGCAAAACTGTGACGTTCGCTTGA")
file.close()

file = open("bookishbubs_test1.txt", "r")
headers = getheader(file)
print(headers)
file.close()

标签: pythonfunctiondictionary

解决方案


推荐阅读