首页 > 解决方案 > 提取括号和嵌套括号之间的字符串

问题描述

所以我有一个文本和标题文件,(标题以“;”开头)

;star/stellar_(class(ification))_(chart)

Hertz-sprussels classification of stars is shows us . . .

我想做的是让它被“_”分割成 ['star/stellar','(class(ification))','(chart)'],通过它们进行交互并提取括号中的内容,例如'(class(ification))'to{'class':'ification'}(chart)to ['chart']。到目前为止我所做的只是分裂部分

for ln in open(file,"r").read().split("\n"):
    if ln.startswith(";"):
        keys=ln[1:].split("_")

我有办法提取括号中的位,但我很难找到一种按顺序支持嵌套括号的方法。我已经尝试过类似re.findall('\(([^)]+)',ln)但返回的事情['star/stellar', '(class', 'chart']。有任何想法吗?

标签: pythonpython-3.x

解决方案


您可以(再次)在括号上拆分,然后进行一些清理:

x = ['star/stellar','(class(ification))','(chart)']

for v in x:
  y = v.split('(')
  y = [a.replace(')','') for a in y if a != '']
  if len(y) > 1:
    print(dict([y]))
  else:
    print(y)

给出:

['star/stellar']
{'class': 'ification'}
['chart']

推荐阅读