Python中的未知错误

0 投票
5 回答
2239 浏览
提问于 2025-04-17 12:48

我遇到了一个奇怪的缩进错误,搞得我很困惑,找不到原因。就我所知,自从上次它正常工作以来,我并没有修改这个文件。

补充:好吧,结果是我不小心修改了它(显然自上次以来肯定有些地方变了)。我在编辑器里按了一个快捷键,把一些制表符变成了空格。谢谢大家!

错误出现在第100行:可以用ctrl f搜索“###”。

#!/usr/bin/env python
import sys
from collections import deque #high performance queue "deck"

class Node(object):
        def __init__(self,x,y,history):
                self.locationx = x
                self.locationy = y
                self.data = None
                self.history = history #previous node to go backwards

def printNodePathTrace(inNode,width,height,mapTerrain,frontier):
    #travel backward through node history until history == None is reached
    #print off map of path
    mapPath = mapTerrain
    for i in range(width): #fill map with blanks
        for j in range(height):
            mapPath[i][j] = '-'

    #print frontier list
    print "length of frontier"
    print len(frontier)
    for item in frontier:

        #print item.locationy
        #print item.locationx
        mapPath[item.locationy][item.locationx] = '*'

    #print path found
    done = 0
    count = 0
    currentNode = inNode
    while(done == 0 and count < 50):
        mapPath[currentNode.locationy][currentNode.locationx] = '#'
        if currentNode.history == None:
            done = 1
        currentNode = currentNode.history
        count += 1
    printMap(mapPath)

def printMap(mapTerrain): #horizontal right positive x, verticle down positive y
        for i in mapTerrain:
            for j in i:
                sys.stdout.write(j)
            sys.stdout.write('\n')

def printMapStartAndGoal(mapTerrain,startX,startY,goalX,goalY):
    #Y is row, X is column. Y is vertical, X is horizontal
    temp1 = mapTerrain[startY][startX]
    temp2 = mapTerrain[goalY][goalX]
    mapTerrain[startY][startX] = 'S'
    mapTerrain[goalY][goalX] = 'G'
    printMap(mapTerrain)
    mapTerrain[startY][startX] = temp1
    mapTerrain[goalY][goalX] = temp2

def main():
    #Input map
    #Your program should be able to read a map file in the following format.
    #Width Height
    #StartX StartY
    #GoalX GoalY
    #map
    searchMode = "BFS" #options are BFS, LC, ID, A*1, A*2

    logfile = open("smallmap2.txt", "r")
    [width,height] = map(int,logfile.readline().split())
    [startX,startY] = map(int,logfile.readline().split())
    [goalX,goalY] = map(int,logfile.readline().split())

    mapTerrainInput = logfile.read()
    mapTerrain = map(list,mapTerrainInput.splitlines())
    #map the list function to mapTerrainInput split into lines without '\n'

    printMapStartAndGoal(mapTerrain,startX,startY,goalX,goalY)

    print mapTerrain
    printMap(mapTerrain)

    closedList = [] #contains list of nodes visited already
    frontier = deque([])
    startNode = Node(startX,startY,None)

    #check if node is a goal node
    #add node to closed list
    #add expansions to frontier list (not ones on closed list)
    #Repeat with next node in Frontier

    goalFound = 0 ### there's an error with this line's indentation???
    iterationCount = 0
    currentNode = startNode
    while goalFound == 0 and iterationCount < 500: #stop when goal is found
            if (currentNode.locationx == goalX and currentNode.locationy == goalY):
                    goalFound = 1
                    break

            closedList.append(currentNode)
            #expand node - currently not checking the closed list
            if (currentNode.locationy > 0): #can expand up
                frontier.append(Node(currentNode.locationx,currentNode.locationy - 1,currentNode))
            if (currentNode.locationy < height - 1): #can expand down
                frontier.append(Node(currentNode.locationx,currentNode.locationy + 1,currentNode))
            if (currentNode.locationx > 0): #can expand left
                frontier.append(Node(currentNode.locationx - 1,currentNode.locationy,currentNode))
            if (currentNode.locationx < width -1): #can expand right
                frontier.append(Node(currentNode.locationx + 1,currentNode.locationy,currentNode))
            #done expanding

            currentNode = frontier.popleft()
            iterationCount += 1


    print currentNode.history
    print currentNode.locationx
    print currentNode.locationy

    printNodePathTrace(currentNode,width,height,mapTerrain,closedList)


if __name__ == '__main__':
    main()

5 个回答

3

你很可能在代码中混用了制表符和空格。选择一种方式,然后一直使用这种方式就好了。

6

我从StackOverflow上复制了你的代码,结果没有出现错误。ideone

通常,这种错误是因为混用了制表符和空格。看你的代码源文件,我发现了问题。下面是你在Visual Studio中代码的样子,空白字符是可见的:

在这里输入图片描述

解决办法

把制表符转换成空格。

  • 如果你的编辑器有把制表符转换成空格的选项,使用这个功能,你就能看到问题所在。
  • 如果你的编辑器可以把制表符的宽度改成8,试试这样做,你会看到问题。
  • 如果你的编辑器有显示空白字符的选项,试着打开它。
  • 否则,可以尝试删除出错行前面的所有空白,然后再用空格键重新添加空格,确保是用空格键。
  • 或者直接把你的代码从StackOverflow复制回你的文件并保存,因为StackOverflow似乎已经为你修复了这个问题。
5

正如其他回答提到的,你的问题在于你混用了制表符和空格,下面是一些证据:

在这里输入图片描述

我在“编辑”你的回答时截了这张屏幕截图,然后搜索了四个空格。所有四个空格的地方都被高亮显示为黄色。

注意,在goalFound = 0之前的空格被高亮了,但之前的行却没有高亮(这说明用了制表符)。

在缩进时,绝对不要混用制表符和空格,因为这样会很难发现错误。Python把制表符当作八个空格来处理,但根据你使用的编辑器,制表符可能看起来等于四个空格(或者其他数字)。所以即使你的代码看起来缩进是正确的,Python实际上看到的却是这样的:

def main():
        #... all previous lines used tabs
        #Repeat with next node in Frontier

    goalFound = 0

撰写回答