如何读取文本文件并将其逐行放入"checkBrackets"方法中?



我正试图用checkBrackets((的附加方法构建一个堆栈ADT,该方法的返回是堆栈中的括号是否匹配。

代码

class Stack:
def __init__(self):
self.top = []
def isEmpty(self):
if self.top == []:
return True
else:
return False
def size(self):
print(len(self.top))
def clear(self):
self.top = []
def push(self, item):
a = len(self.top)
self.top.insert(-(a+1), item)
def pop(self):
print(self.top.pop(0))
def peek(self):
print(self.top[0])
def checkBrackets(self):
myStack = Stack()
for ch in self.top:
if ch in ('{[('):
myStack.push(ch)
elif ch in ('}])'):
if myStack.isEmpty():
return "not matched"
else:
left = myStack.pop()
if ((ch == '}' and left != '{')
or (ch == ']' and left != '[')
or (ch == ')' and left != '(')
):
return "not matched"
if myStack.isEmpty() == True:
return "matched"
else:
return "not matched"
def print(self):
print(self.top)
def main():
msg = "Enter a command: pop, push, peek, size, clear, empty, p(rint), m(atch), q(uit)"
print(msg)
myStack = Stack()
while True:
command = input().split()
if command[0] == 'empty':
print(myStack.isEmpty())
elif command[0] == 'size':
myStack.size()
elif command[0] == 'clear':
myStack.clear()
elif command[0] == 'pop':
myStack.pop()
elif command[0] == 'push':
myStack.push(command[1])
elif command[0] == 'peek':
myStack.peek()
elif command[0] == 'p':
myStack.print()
elif command[0] == 'm':
inFile = open("text.txt", 'r')
while True:
line = inFile.readline()
if line == "":
break
for i in line:
myLine = Stack()
myLine.top.append(i)
print(myLine.top, end = "")
print(myLine.checkBrackets())
# myLine.push(i)
# print(myLine.checkBrackets())
inFile.close()
main()

如果其他ADT方法让你感到困惑,那就忘掉它们吧。我只是在问checkBracket方法。。。

文本文件如下所示:

[()]
{[()]}
{([])}
[ ] [ ] [ ] ( ) { }
[ [ [ { { ( ( ( ) ) ) } } ] ] ] ( )
{())

我该怎么修?

inFile也应该具有函数readlines

所以你可以这样做:

inFile = open("text.txt", 'r')
lines = inFile.readlines()
for line in lines:
line.checkBrackets()

这包含了整条线。目前,您正在循环单行的元素,并对每个元素应用检查,而不是对整行进行检查。

相关内容

最新更新