我正在尝试编写一个小脚本,以检查作为命令行参数传递的文件的括号是否正确。
我创建了一个异常来处理函数停止点,但似乎无法正确引发它。
当我在Python解释器中测试代码时,它似乎可以工作(即,它识别出应该引发异常),但是当我使用我拥有的示例文件(带有严重括号)测试文件时,它仍然会打印证明它已成功检查
你有什么想法吗?
最好
代码:
import sys
from stack import *
class BracketException(Exception) :
"""
Exception qui gère les problèmes de parenthesage : mauvaise parenthèse,
mauvais placement etc...
"""
def __init__(self, char, lineNumber, charNumber) :
self.char = char
self.lineNumber = lineNumber
self.charNumber = charNumber
def __str__(self) :
return(self.char + " at line " + str(self.lineNumber) + " char " + str(self.charNumber))
def checker(file) :
lineNumber = 1
charNumber = 1
stacked = Stack()
openers = ["(", "[", "{"]
closers = [")", "]", "}"]
inChannel = open(file, "r")
for line in file :
for char in line :
if char in openers :
stacked.push([char, lineNumber, charNumber])
print(stacked.top())
elif char in closers :
try :
if openers[closers.index(char)] == stacked.top()[0] :
stacked.pop()
else :
raise BracketException(char, lineNumber, charNumber)
except StackEmptyError :
raise BracketException(char, lineNumber, charNumber)
charNumber += 1
charNumber = 1
lineNumber += 1
inChannel.close()
if not stacked.is_empty() :
raise BracketException(stacked.top()[i] for i in range(3))
def __main__() :
try :
fichier = sys.argv[1]
checker(fichier)
print("it's checked !")
except BracketException as ex :
print(ex)
except IndexError :
print("Wrong number of parameters")
except Exception as e :
print(e)
if __name__ == "__main__" :
__main__()
答案 0 :(得分:3)
您要遍历给定的文件名,而不是创建的文件句柄。文件名中可能没有不平衡的括号,因此也不例外。
def checker(file) : lineNumber = 1 charNumber = 1 stacked = Stack() openers = ["(", "[", "{"] closers = [")", "]", "}"] inChannel = open(file, "r") # file handle is inChannel for line in file : # iterating over file name, not file handle
您应该切换到
with open(file, "r") as inChannel:
for line in inChannel :
要确保即使抛出异常也要关闭文件-它是文件处理的首选方式,请参见docs.python.org - reading and writing files
我无法测试(没有堆栈模块-如果需要,我使用列表),但这应该更快:
def checker(filename) :
lineNumber = 1
charNumber = 1
stacked = Stack()
openers = set( "{[(") # sets are better suited for test of "in"
closers = set( "}])") # same
# mapping between closing bracket at hand and what should be on the stack
# also faster then .index()ing into a list
open_for_close = { ")":"(","}":"{","]":"[" }
with open(filename, "r") as f:
for line in f: # iterate over the filehandle
for char in line:
if char in openers:
stacked.push([char, lineNumber, charNumber])
print(stacked.top())
elif char in closers:
try :
if open_for_close[char] == stacked.top()[0] :
stacked.pop()
else :
raise BracketException(char, lineNumber, charNumber)
except StackEmptyError :
raise BracketException(char, lineNumber, charNumber)
charNumber += 1
charNumber = 1
lineNumber += 1
if not stacked.is_empty() :
raise BracketException(stacked.top()[i] for i in range(3))