38

IndentationError: 意外的 unindent 为什么???

#!/usr/bin/python
import sys
class Seq:
    def __init__(self, id, adnseq, colen):
        self.id     = id
        self.dna    = adnseq
        self.cdnlen = colen
        self.prot   = ""
    def __str__(self):
        return ">%s\n%s\n" % (self.id, self.prot)
    def translate(self, transtable):
        self.prot = ""
        for i in range(0,len(self.dna),self.cdnlen):
            codon = self.dna[i:i+self.cdnlen]
            aa    = transtable[codon]
            self.prot += aa
    def parseCommandOptions(cmdargs):
        tfname = cmdargs[1]
        sfname = cmdargs[2]
        return (tfname, sfname)
    def readTTable(fname):
        try:
            ttable = {}
            cdnlen = -1
            tfile = open(fname, "r")
            for line in tfile:
                linearr = line.split()
                codon   = linearr[0]
                cdnlen  = len(codon)
                aa      = linearr[1]
                ttable[codon] = aa
            tfile.close()
            return (ttable, cdnlen)
    def translateSData(sfname, cdnlen, ttable):
        try: 
            sequences = []
            seqf = open(seq_fname, "r")
            line = seqf.readline()
            while line:
                if line[0] == ">":
                    id = line[1:len(line)].strip()
                    seq = ""
                    line = seqf.readline()
                    while line and line[0] != '>':
                        seq += line.strip()
                        line = seqf.readline()  
                    sequence = Seq(id, seq, cdnlen)
                    sequence.translate(ttable)
                    sequences.append(sequence)
            seqf.close()
            return sequences    
    if __name__ == "__main__":
        (trans_table_fname, seq_fname) = parseCommandOptions(sys.argv)
        (transtable, colen) = readTTable(trans_table_fname)
        seqs = translateSData(seq_fname, colen, transtable)
        for s in seqs:
            print s

它说:

 def translateSeqData(sfname, cdnlen, ttable):
   ^
IndentationError: unexpected unindent

为什么?我检查了数千次,我找不到问题所在。我只使用了制表符,没有空格。另外,有时它会要求定义类。那样可以么?

4

4 回答 4

99

这是因为你有:

def readTTable(fname):
    try:

except块后没有匹配try:块。每个try必须至少有一个匹配项except

请参阅 Python 教程的错误和异常部分。

于 2012-04-20T03:01:57.393 回答
8

你没有完成你的try陈述。你也需要并且except在那里。

于 2012-04-20T03:02:43.680 回答
2

此错误实际上可能在报告错误的代码中。请参阅例如,如果您有如下语法错误,您将收到缩进错误。语法错误实际上在“except”旁边,因为它后面应该包含一个“:”。

try:
    #do something
except
    print 'error/exception'


def printError(e):
    print e

如果将上面的“except”更改为“except:”,错误就会消失。

祝你好运。

于 2012-08-10T16:02:28.133 回答
1

@MaxPython 下面的答案缺少语法":"

    try:
       #do something
    except:
      # print 'error/exception'


    def printError(e):
        print e
于 2020-09-10T21:22:21.550 回答