Python - 检查所有分隔符是否匹配并关闭

时间:2018-05-03 10:51:05

标签: python delimiter

我正在尝试编写一个Python程序,它接受一个字符串并检查是否所有分隔符都已匹配并关闭。

我发现this程序执行此操作,但遗憾的是它不适用于字符串引号。不幸的是,我不完全理解该程序是如何工作的,所以我无法修复它。有人可以告诉我如何更改程序以使用字符串分隔符('和")。

我目前的代码是:

delimOpens = ['[', ']', '(', ')', '{', '}', '"', "'"]
delimCloseToOpen = {']':'[', ')':'(', '}':'{', '"':'"', "'":"'"}

def check_match(source):
    delimStack = ['sentinel']
    for c in source:
        if c in delimOpens:
            delimStack.append(c)
        elif c in delimCloseToOpen:
            if delimCloseToOpen[c] != delimStack.pop():
                return False
    return (len(delimStack) == 1)

if __name__ == "__main__":
    print(check_match('{(abc)22}[14(xyz)2]'))
    print(check_match('[ { ] }'))
    print(check_match('{ (x) } ['))
    print(check_match('This is "hello" world'))
    print(check_match('This is "hello world'))

问题是代码对有效字符串返回false:

print(check_match('This is "hello" world'))

1 个答案:

答案 0 :(得分:1)

即使您遇到关闭",也会在堆栈上推送"

解决方案:提前检查当前角色是否可以关闭某些内容以及堆栈顶部是否存在某些内容(delimStack[-1]):

delimOpens = ['[', ']', '(', ')', '{', '}', '"', "'"]
delimCloseToOpen = {']':'[', ')':'(', '}':'{', '"':'"', "'":"'"}

def check_match(source):
    delimStack = ['sentinel']
    for c in source:
        if c in delimCloseToOpen and delimCloseToOpen[c] == delimStack[-1]:
            delimStack.pop()
        elif c in delimOpens:
            delimStack.append(c)
        elif c in delimCloseToOpen:
            if delimCloseToOpen[c] != delimStack.pop():
                return False
    return (len(delimStack) == 1)

if __name__ == "__main__":
    print(check_match('{(abc)22}[14(xyz)2]'))
    print(check_match('[ { ] }'))
    print(check_match('{ (x) } ['))
    print(check_match('This is "hello" world'))
    print(check_match('This is "hello world'))

输出:

$ python3 so_50153245.py
True
False
False
True
False