如何忽略括号中的嵌套括号之间的子字符串而提取括号之间的子字符串?

时间:2018-11-23 04:55:37

标签: python

我有一个字符串:

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'

如何仅提取括号之间的子字符串,并且每个子字符串中不包含任何括号?因此,在我的示例中,我需要两个输出:“ s2:0.4186036213,s3:0.4186036213”和“ s4:0.1429514535,s5:0.1429514535”。

3 个答案:

答案 0 :(得分:1)

您可以使用regular rexpressions

import re

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'
re.findall(r'\(([^\(\)]*)\)', phy)
# ['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']

这将捕获所有用开括号括住的非括号括起来的内容。但是,它不能验证正确的嵌套级别。

答案 1 :(得分:1)

尝试一下:

from collections import defaultdict
bracket_dict = defaultdict(int)
bracket_dict_ ={
    '(':')',
    '{':'}',
    '[':']'
}
bracket_dict.update(bracket_dict_)
bracket_list = bracket_dict.keys()

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654);'
inner_items=[]
brackets = []
start_index = None

for i in range(len(phy)):
    if phy[i] in bracket_list:
        start_index = i
        brackets.append(phy[i])

    if brackets:
        if phy[i] == bracket_dict[brackets[-1]]:
            inner_items.append(phy[start_index+1 : i])
            brackets.append(phy[i])
print(inner_items)
#['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']

答案 2 :(得分:1)

使用正则表达式:

import re

reg = re.compile(r'[(]([^()]+)[)]')

phy = '(s1:0.6507212936,((s2:0.4186036213,s3:0.4186036213):0.1428084058,((s4:0.1429514535,s5:0.1429514535):0.1695879844,s6:0.3125394379):0.2488725892):0.08930926654)'

print(reg.findall(phy))

输出:

C:\Users\Desktop>py x.py
['s2:0.4186036213,s3:0.4186036213', 's4:0.1429514535,s5:0.1429514535']