python括号详解_在python中解析嵌套括号,按级别抓取内容

Apparently this problem comes up fairly often, after reading

and thinking about the problem for a while, i wrote a function to return the content contained inside an arbitrary number of nested ()

The function could easily be extended to any regular expression object, posting here for your thoughts and considerations.

any refactoring advice would be appreciated

(note, i'm new to python still, and didn't feel like figuring out how to raise exceptions or whatever, so i just had the function return 'fail' if it couldin't figure out what was going on)

Edited function to take into account comments:

def ParseNestedParen(string, level):

"""

Return string contained in nested (), indexing i = level

"""

CountLeft = len(re.findall("\(", string))

CountRight = len(re.findall("\)", string))

if CountLeft == CountRight:

LeftRightIndex = [x for x in zip(

[Left.start()+1 for Left in re.finditer('\(', string)],

reversed([Right.start() for Right in re.finditer('\)', string)]))]

elif CountLeft > CountRight:

return ParseNestedParen(string + ')', level)

elif CountLeft < CountRight:

return ParseNestedParen('(' + string, level)

return string[LeftRightIndex[level][0]:LeftRightIndex[level][1]]

解决方案

You don't make it clear exactly what the specification of your function is, but this behaviour seems wrong to me:

>>> ParseNestedParen('(a)(b)(c)', 0)

['a)(b)(c']

>>> nested_paren.ParseNestedParen('(a)(b)(c)', 1)

['b']

>>> nested_paren.ParseNestedParen('(a)(b)(c)', 2)

['']

Other comments on your code:

Docstring says "generate", but function returns a list, not a generator.

Since only one string is ever returned, why return it in a list?

Under what circumstances can the function return the string fail?

Repeatedly calling re.findall and then throwing away the result is wasteful.

You attempt to rebalance the parentheses in the string, but you do so only one parenthesis at a time:

>>> ParseNestedParen(')' * 1000, 1)

RuntimeError: maximum recursion depth exceeded while calling a Python object

As Thomi said in the question you linked to, "regular expressions really are the wrong tool for the job!"

The usual way to parse nested expressions is to use a stack, along these lines:

def parenthetic_contents(string):

"""Generate parenthesized contents in string as pairs (level, contents)."""

stack = []

for i, c in enumerate(string):

if c == '(':

stack.append(i)

elif c == ')' and stack:

start = stack.pop()

yield (len(stack), string[start + 1: i])

>>> list(parenthetic_contents('(a(b(c)(d)e)(f)g)'))

[(2, 'c'), (2, 'd'), (1, 'b(c)(d)e'), (1, 'f'), (0, 'a(b(c)(d)e)(f)g')]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值