解析文本并返回Python中不匹配括号的列表

时间:2018-08-13 01:29:33

标签: python python-3.x stack

我需要解析一些文本并确定哪些括号未关闭,并返回将其关闭的括号列表,例如

如果这是输入的字符串:

({([])

然后函数应返回一个括号列表以关闭不匹配的集合:

['}', ')']

基本上关闭了不匹配的集合。

这是我当前拥有的代码:

def evaluate(str):
stack = []
missing = []
pushChars, popChars = "({[", ")}]"
for c in str:
    if c in popChars:
        matching = pushChars[popChars.index(c)]
        if not len(stack) or stack[len(stack) - 1] != matching:
            missing.append(c)
        else:
            stack.pop()
        continue
    if c in pushChars:
        stack.append(c)
return missing

2 个答案:

答案 0 :(得分:1)

您可以创建一个类来解析文本对,并且如果找不到结束值,则可以将无效字符追加到未结束的字符列表中:

class Parse:
  def __init__(self, _str, _to_find = None):
    self.brackets = _str
    self.converter = {'(':')', '[':']', '{':'}', ')':'(', ']':'[', '}':'{'}
    self.search_for = _to_find
    self.flagged = []
    self.parse()
  def parse(self):
    _current = next(self.brackets, None)
    if _current is None and self.search_for is not None:
      self.flagged.append(self.search_for)
    elif _current is not None:
      if _current != self.search_for:
        _result = Parse(self.brackets, self.converter[_current])
        self.flagged.extend(_result.flagged)
        self.brackets = _result.brackets
        self.parse()


p = Parse(iter('({([])'))
print(p.flagged)

输出:

['}', ')']

但是,请注意,如果找到有效序列,则flagged将是一个空列表([]):

p = Parse(iter('{{()}}'))
print(p.flagged)

输出:

[]

答案 1 :(得分:0)

def evaluate(s):
    stack = []
    result = []
    braces = {'(': ')', '{': '}', '[': ']'}

    for x in s:
        if x in braces.keys():
            stack.append(x)
        elif x == braces[stack[-1]]:
            stack.pop()
        else:
            raise Exception('Non-valid bracket sequence')

    while stack:
        result.append(braces[stack.pop()])

    return result

print(evaluate('({([])'))

输出

['}', ')']