我编写了一个代码来读取文件并检查括号是否平衡。我想修改这段代码,它读取文件并忽略文字字符串和文字字符中的括号,但我不太清楚如何继续这样做。谁能帮助我并给我一个想法?继承我的代码:
def isValidSource(fileName):
textFile = open(fileName)
readFile = textFile.read()
stack = []
for line in readFile:
for token in line:
if token in "{[(":
stack.append( token )
elif token in "}])":
if not len(stack):
return False, "Delimiters are not balanced"
else :
left = stack.pop()
print stack
if (token == "}" and left != "{") or \
(token == "]" and left != "[") or \
(token == ")" and left != "("):
return False, "Delimiters are not balanced"
return not len(stack), "The stack is empty; all delimiters are paired and balanced"
答案 0 :(得分:1)
您可以保留一个布尔标志来指示您是否在字符串中。如果您在for token in line
循环中遇到"
,请切换该标记。如果设置了标志,则可以跳过平衡检查逻辑。