Python:获取适当大括号和符号之间的部分字符串

Python: Get part of string between appropriate braces and symbols

如果我在文本文件中有以下内容:

{
fun cake(){
"im cute"
subfun notcake(){
"dont close the question!"
}
}
fun notcute(){
"Did you just say..."
}
}

我想在有趣的蛋糕()的两个括号之间得到东西。 那些特殊的大括号,以及与左大括号和右大括号匹配的对,这样我就不会得到其他大括号的字符串。

(重点以粗体突出显示)

这是我为您创建的通用库函数

def makePairs(code: str, bracket_list = ['[', '{', '(', '<']) -> dict:
    """
    Pair Maker
    =========
        Finds and creates corresponding pairs of all types of brackets given in the 'bracket_list' present in the 'code'.

        Parameters
        ----------
        1. Code : str - given string of code
        2. Bracket List : list - all types of brackets whose pair has to be searched and mapped

        Returns
        -------
        A dictionary that maps an opening bracket position to corresponding closing bracket position

        Example
        -------
        >>> bracePairs = makePairs(code)\n
        >>> for open, close in bracePairs.items():\n
        >>>    print(code[open : close+1])
    """
    
    naivePairs = { '{':'}', '[':']', '(':')', '<':'>' }
    pairs:dict = {}                                                         # maps '{' position to corresponding '}' position
    openBraceStack = []                                                     # will store the consecutive brace openings
    for pos, char in enumerate(code):
        if char in naivePairs.keys(): openBraceStack.append(pos)            # if char is '{', push it into the 'openBraceStack'
        elif char in naivePairs.values(): pairs[openBraceStack.pop()] = pos # if char is '}', pop the last '{' from 'openBraceStack' and store this pair into 'pairs'
    
    return pairs

用法(在它的文档字符串中也提供了):

bracePairs = makePairs(code)
for open, close in bracePairs.items():
   print(code[open : close+1], '\n\n\n')

查询具体用法:

bracePairs = makePairs(code)
cakeOpen = code.find('{', code.find('fun cake'))            # find the first '{' after cake function
cakeCode = code[cakeOpen + 1 : bracePairs[cakeOpen]]
print(cakeCode)