我需要创建一个函数,该函数使用堆栈来查看html文件是否平衡了开始和结束标记。这个问题让您假设html是逐行显示的,而不必担心缩进。我下面的程序在我不平衡结束标签时工作,比如< html >>,这就是我要问的所有问题,但我正在尝试编辑我的函数,这样它就会看到不平衡的html开始标签。像< html html >这样的内容会被我的函数注意到,但是像<< >> >这样的内容不会被注意到。我想我可以向我的函数添加另一个语句,比如"if ch == '<‘and not stack.is_empty():return False“,但是我不确定我应该把它放在函数中的什么位置。
class Stack:
""" Last in first out"""
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def peek(self):
return self.items[len(self.items - 1)]
def push(self,item):
return self.items.append(item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def HTMLCheck(newfile):
# How to see if << is covered
with open(newfile) as file:
stack = Stack()
list1 = list()
for line in file:
line = line.rstrip()
list1.append(line)
index = 0
while index < len(list1):
for ch in list1[index]:
if ch == '<':
stack.push(ch)
elif ch == '>':
if stack.is_empty():
return False
else:
stack.pop()
index += 1
return True
print(HTMLCheck('HW5.txt'))
发布于 2018-08-09 07:11:42
def HTMLCheck(newfile):
# How to see if << is covered
with open(newfile) as file:
stack = Stack()
list1 = list()
for line in file:
line = line.rstrip()
list1.append(line)
index = 0
while index < len(list1):
for ch in list1[index]:
if ch == '<':
stack.push(ch)
elif ch == '>':
if stack.is_empty():
return False
else:
stack.pop()
index += 1
return stack.is_empty() # if the stack is not empty then it was not balanced ...
发布于 2020-02-12 01:55:17
另一种解决方案。我对算法做了一点改进,还检查了标签的全名。
import re
def tagChecker(symbolString):
s = Stack()
pattern = re.compile('<.*?>')
pattern_close = re.compile('</.*?>')
tag_list = re.findall(pattern, html_str)
balanced = True
index = 0
while index < len(tag_list) and balanced:
tag = tag_list[index]
if not pattern_close.match(tag):
s.push(tag)
else:
if s.isEmpty() or str.replace(tag, '/', '') != s.peek():
# s.peek() - function, which returns top of the stack without removing
balanced = False
else:
s.pop()
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
https://stackoverflow.com/questions/51756840
复制相似问题