python - 提取括号和嵌套括号之间的字符串
问题描述
所以我有一个文本和标题文件,(标题以“;”开头)
;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']
。有任何想法吗?
解决方案
您可以(再次)在括号上拆分,然后进行一些清理:
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']
推荐阅读
- vbscript - DeleteFile 或 CopyFile 失败并出现错误 32813
- javascript - 谷歌浏览器不允许存储
- kubernetes - Submariner “发现网络详细信息 CIDR” 未完成
- bigcartel - 如何在 BigCartel(Luna 主题)中编辑幻灯片大小?
- c - 在STM32上测量信号频率
- c++ - 从 initializer_list 构造 string_views 的向量
- ios - 使用 Cordova 10 的应用内 AJAX 无法在 iOS 中运行
- loopbackjs - 覆盖 Loopback3 中的 patchAttributes 方法
- java - 强制转换不适用于嵌套列表对象类型并返回空列表(列表
- >)
- angular - Angular 2+ 单元测试中的存根文件导入