我需要一種方法,在python中給出一串文本,將它的內容分隔成一個列表,用3個參數分隔 - 最外括號與最外括號對普通文本,保留原始語法。將括號內的字符串與括號中的內容分開vs對比括號中的內容
例如,給定一個字符串
(([a] b) c) [d] (e) f
預期產出將是這個名單:
['(([a] b) c)', '[d]', '(e)', ' f']
我試着用正則表達式的幾件事情,如
\[.+?\]|\(.+?\)|[\w+ ?]+
這給了我
>>> re.findall(r'\[.+?\]|\(.+?\)|[\w+ ?]+', '(([a] b) c) [d] (e) f')
['(([a] b)', ' c ', ' ', '[d]', ' ', '(e)', ' f']
(C項錯誤的列表)
我也試過它的貪婪版本,
\[.+\]|\(.+\)|[\w+ ?]+
但當串具有相同類型的獨立經營卻不盡如人意:
>>> re.findall(r'\[.+\]|\(.+\)|[\w+ ?]+', '(([a] b) c) [d] (e) f')
['(([a] b) c) [d] (e)', ' f']
然後我從正則表達式轉移到使用堆棧來代替:
>>> def parenthetic_contents(string):
stack = []
for i, c in enumerate(string):
if c == '(' or c == '[':
stack.append(i)
elif (c == ')' or c == ']'):
start = stack.pop()
yield (len(stack), string[start + 0:i+1])
,除了我這偉大的工作,爲括號和圓括號都沒有獲得純文本的方式(或者我做什麼,但我不知道這件事?):
>>> list(parenthetic_contents('(([a] b) c) [d] (e) f'))
[(2, '[a]'), (1, '([a] b)'), (0, '(([a] b) c)'), (0, '[d]'), (0, '(e)')]
我不熟悉pyparsing。它首先看起來好像nestedExpr()會做到這一點,但它只需要一個分隔符(()或[],但不是兩者),這對我不起作用。
我現在都沒有想法。歡迎大家提出意見。
作爲一般規則,正則表達式無法與您的括號相匹配,因爲它們不會「打」(因爲它是)打開和關閉項目。這與[下推自動機](http://en.wikipedia.org/wiki/Pushdown_automaton)基本上比[有限狀態機]更強大(http://en.wikipedia.org/wiki/Finite_automaton )。更多:http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Pushdown_automaton.html – torek