Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中解析文本并返回不匹配括号的列表_Python_Python 3.x_Stack - Fatal编程技术网

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

在Python中解析文本并返回不匹配括号的列表,python,python-3.x,stack,Python,Python 3.x,Stack,我需要解析一些文本,确定哪些括号未关闭,并返回一个括号列表,这些括号将关闭它们,例如 如果这是输入的字符串: ({([]) 然后,函数应返回括号列表,以关闭不匹配的集合: ['}', ')'] 基本上关闭了不匹配的集合 这是我目前拥有的代码: def evaluate(str): stack = [] missing = [] pushChars, popChars = "({[", ")}]" for c in str: if c in popChars: matc

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

如果这是输入的字符串:

({([])
然后,函数应返回括号列表,以关闭不匹配的集合:

['}', ')']
基本上关闭了不匹配的集合

这是我目前拥有的代码:

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

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

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)
输出:

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

输出:

['}', ')']
[]
输出

['}', ')']

但是如果你有一个错误的括号序列,比如
({[}'
),我会说(对于这个应用程序来说),它应该返回一个空的listI-added解决方案,在这种情况下会引发异常。所以如果括号序列无效(在上面的注释中说明)它将在标记的列表中?@AntidiseStablementArianism只有没有结尾等价物的字符才会添加到列表中(如您所需的输出)。哦,我明白了。谢谢