我应该如何在python中为单个操作编写多个循环

时间:2017-07-16 01:57:11

标签: python loops parsing

我是学习python的新手,我真的需要完成这项工作,我真的不知道如何在一个巨大的信息海洋中寻找答案。

我正在使用PDB解析器,我有以下代码:

lastprocessed

有了这个结果:

  

3caq | {' 1':{'同义词':' delta(4)-3-酮类固醇5-β-还原酶,aldo-keto还原酶家族1成员d1' ,'链接' a,b',' misc':'','分子':&# 39; 3-氧代-5-β-甾体4-脱氢酶',' ec_number':' 1.3.1.3'' ec':' 39; 1.3.1.3','工程':'是'}}

问题是我不使用单个文件(在"文件名"下定义)但我有数百个文件,我需要从中提取"标题&# 34;,并且只保留"化合物"所述标题的变量。

我知道我必须为要完成的事情编写循环,我尝试了以下内容:

lastprocessed

然后我提供解析器,但是我收到错误。

#Calling the module
from Bio.PDB.PDBParser import PDBParser

#Defining some variables
parser = PDBParser(PERMISSIVE=1)
structure_id= "3caq"
filename = "3caq.pdb"

#This is the actual task to be done
structure = parser.get_structure(structure_id, filename)

#What I'm interested in doing
compound = structure.header['compound']
print structure_id + " |", compound

我非常确定循环没有正确写入。

所以,如果我可以通过我可以检查的资源或使用正确的命令正确编写该循环,我会非常感激。

最好的问候。

2 个答案:

答案 0 :(得分:0)

明确的理解可以帮助您解决这个问题。

您需要遍历许多结构,以便使用for循环进行良好的选择。我建议你使用列表而不是设置来存储结构和文件名。

filenames = ["3caq", "2zb7" ]
structures = ["3caq.pdb", "2bz7.pdb"]

现在你可以按结构的长度进行迭代。

for each in range(len(structures)):
    structure = parser.get_structure(structures[each], filenames[each])

    compound = structure.header['compound']
    print structure_id + " |", compound

如果这对您有用,请告诉我。

答案 1 :(得分:0)

您收到错误是因为当["3caq.pdb"]需要字符串(get_structure())时,您传递了一个列表("3caq.pdb")。

以下是支持多个文件的方法:

from Bio.PDB.PDBParser import PDBParser

files = {"3caq.pdb", "2bz7.pdb"}

for filename in files:
    # Defining some variables
    parser = PDBParser(PERMISSIVE=1)

    # Drop ".pdb" from filename to get structure_id
    structure_id = filename.split('.')[0]

    # This is the actual task to be done
    structure = parser.get_structure(structure_id, filename)

    # What I'm interested in doing
    compound = structure.header['compound']

    print("{} | {}".format(structure_id, compound))

为了使你的代码更好,我会把它写成一个单独的函数:

from Bio.PDB.PDBParser import PDBParser

def get_compound_header(filename):
    # Defining some variables
    parser = PDBParser(PERMISSIVE=1)

    # Drop ".pdb" from filename to get structure_id
    structure_id = filename.split('.')[0]

    # This is the actual task to be done
    structure = parser.get_structure(structure_id, filename)

    # What I'm interested in doing
    compound = structure.header['compound']

    return "{} | {}".format(structure_id, compound)


# Main function
if __name__ == "__main__":

    files = {"3caq.pdb", "2bz7.pdb"}

    for filename in files:
        print(get_compound_header(filename))