IndexError:列表索引超出范围错误,如何修复代码?

时间:2018-09-24 06:21:50

标签: python

import os 

import sys

import numpy as np

from proteinss import ProteinSS

map_dssp_3_alphabet = {"H":1,"I":1,"G":1,"E":2,"B":2,"T":3,"S":3, "_":3, "?":3}
map_dssp_8_alphabet = {"H":1,"I":2,"G":3,"E":4,"B":5,"T":6,"S":7, "_":8, "?":8}

def extract_file(ss_file):
    print ("Extracting :"), ss_file

fi = open(ss_file, 'rU')
seq_string = ""
ss_string  = ""
alignments = []
for line in fi:
    if line.startswith("RES:"):
       seq_string = line.split(":")[1].rstrip('\n')

    if line.startswith("DSSP:"):
       ss_string = line.split(":")[1].rstrip('\n')

    if line.startswith("align"):
       alignment = line.split(":")[1].rstrip('\n')
       alignments.append( alignment.split(",")[0:-1] )

seq_l = seq_string.split(",")[0:-1]
ss_l  = ss_string.split(",")[0:-1]

prot = ProteinSS(seq_l, ss_l)

for al_ in alignments:
    prot.add_alignment(al_)

return prot


def prepare_db(cb513_path, db_ofile, db_classes, wsize, alphabet):
    fo1 = open(db_ofile, 'w')
    fo2 = open(db_classes, 'w')


for root, dirs, files in os.walk(cb513_path):
    for name in files:
        if name.endswith(( ".all" )):
            ss_file = root + "/" + name
            prot = extract_file ( ss_file )
            if prot.is_valid():
                s1, s2 = prot.get_db_strings(wsize, map_dssp_3_alphabet, True)
                fo1.write(s1)
                fo2.write(s2)

fo1.close()
fo2.close()


if __name__ == "__main__":
    cb513_path = '../data/CB513'
    classes_ofile   = "../data/db/ss_a3.dat" 

window_width = int( sys.argv[5] ) 
db_ofile = "../data/db/aa_w" + str(window_width) + "_a3.dat"

if sys.argv[2] == "3":
    alphabet = map_dssp_3_alphabet
elif sys.argv[2] == "8":
    alphabet = map_dssp_8_alphabet
else:
    print ("Alphabet not recognized: choose between 3 or 8")
    sys.exit(1)

pubs_data = prepare_db(cb513_path, db_ofile, classes_ofile, window_width, alphabet)

我在:错误:

  

window_width = int(sys.argv [5])

     

IndexError:列表索引超出范围

当我尝试使用spyder运行代码时,编码显示错误列表超出范围错误,我应该更改指定的尺寸还是使用任何其他功能?

这是我用于蛋白质二级结构预测的代码之一,特别是用于创建数据库。

IndexError是Python中最基本,更常见的异常之一,因为每次尝试访问列表范围之外的索引时都会引发该异常,是否是因为我正在尝试访问某些内容在列表的边界之外。

如何解决以上问题?

1 个答案:

答案 0 :(得分:0)

sys.argv被定义为Python中的列表,其中包含您要执行任何程序时传递给脚本的命令行参数。

只需在程序开始时打印sys.argv的长度,就可以在执行列表时检查传递的参数。

在程序开始时在下面添加行:

print(len(sys.argv))

如果从命令行执行以下程序,则从命令行开始

python demo.py 

然后sys.argv的长度为1,而 sys.argv [0] 的值为 demo.py

检查后,可以根据需要修改sys.argv索引值。 希望这能解决您的问题。

P.S。在您的程序中此行写错了:

print ("Extracting :"), ss_file

更正为

 print ("Extracting :"+ ss_file)