我有一個這樣的字符串:'aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'
。從該字符串我想要得到以下結構:['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']
。換句話說,我想分開不同類型括號中的子字符串。Python是否有簡單的字符串解析器?
回答
您需要使用堆棧的方式來跟蹤嵌套層數:
pairs = {'{': '}', '[': ']', '(': ')'}
def parse_groups(string):
stack = []
last = 0
for i, c in enumerate(string):
if c in pairs:
# push onto the stack when we find an opener
if not stack and last < i:
# yield anything *not* grouped
yield string[last:i]
stack.append((c, i))
elif c in pairs:
if stack and pairs[stack[-1][0]] == c:
# Found a closing bracket, pop the stack
start = stack.pop()[1]
if not stack:
# Group fully closed, yield
yield string[start:i + 1]
last = i + 1
else:
raise ValueError('Missing opening parethesis')
if stack:
raise ValueError('Missing closing parethesis')
if last < len(string):
# yield the tail
yield string[last:]
這將產生羣體,轉換爲一個列表,如果你需要一個:
>>> list(parse_groups('aaa(cc(kkk)c)ddd[lll]{m(aa)mm}'))
['aaa', '(cc(kkk)c)', 'ddd', '[lll]', '{m(aa)mm}']
如果括號/括號不均衡,將引發一個異常:
>>> list(parse_groups('aa(bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 19, in parse_groups
ValueError: Missing closing parethesis
>>> list(parse_groups('aa[{bb}}'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
>>> list(parse_groups('aa)bb'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 20, in parse_groups
ValueError: Missing opening parethesis
我想你可以試試Custom String Parser庫(我是它的作者)。它的設計與具有任何邏輯結構數據的工作,所以你可以自定義你想要的方式;)
請確實披露您正在鏈接到您自己的項目;請參閱[FAQ#promotion]。這很好,但它很快被視爲垃圾郵件,而不是幫助OP。 :-) – 2013-03-07 11:50:58
如果你能解決你的問題,我不應該推薦一個庫(即使我是作者)? – 2013-03-07 12:20:54
你可以推薦一個圖書館,但如果它是*你的*項目,請這麼說。 :-) – 2013-03-07 12:22:15
你也可以看看pyparsing。有趣的是,這可以作爲一個堆棧來實現,當你發現{[(並且當你發現時彈出)]時你可以推送字符串片段。
- 1. 簡單的PHP字符串解析
- 2. 簡單NSDateFormatter /字符串解析
- 3. 從JSON字符串到字典的簡單解析器
- 4. Interning字符串是否有助於解析器的性能?
- 5. 是否有NSString的格式字符串解析器?
- 6. Python的解析字符串
- 7. 用於簡單xml節點字符串的Android XML解析器
- 8. 解析C中字符串的最簡單方法是什麼?
- 9. C#中是否有任何連接字符串解析器?
- 10. python解析xml字符串
- 11. 字符串解析 - Python
- 12. 解析字符串 - 在python
- 13. 用Python解析字符串
- 14. 是否有Python模塊來解析原始字符串中的換行符號?
- 15. 腓簡單的HTML DOM解析器查找字符串的任何字符
- 16. Python的字符串解釋和解析
- 17. 解析單個字符串
- 18. C /解析字符串,什麼是我有一個這樣的字符串的最簡單的方法
- 19. 是否有解析字符串來創建C#func的工具?
- 20. 是否有解析用戶代理字符串的好方法?
- 21. 是否有解析冒號和逗號符號的解析器?
- 22. 解析解析字符串
- 23. 從Cocoa中的字符串解析簡單的XML?
- 24. Python的simplejson不分析一個簡單的JSON字符串
- 25. Python字符串和字典解析
- 26. python中的字符串解析
- 27. 解析Python中的字符串3
- 28. python的字符串解析不一致
- 29. 在Python中解析json的字符串
- 30. 解析字符串模式 - Python的
爲什麼你的'(cc(kkk)c)'結構變成'(cc {kkk} c)'? – 2013-03-07 10:38:28
對不起,我犯了一個錯誤。它應該是(cc(kkk)c)。 – Roman 2013-03-07 10:39:15
正確,所以你的括號和括號可以嵌套。 – 2013-03-07 10:39:56