はここで動的に正しい閉じ括弧文字に一致するように自己修正の文法を使用していますpyparsingソリューションです必要な場合は
import re
import ast
def parse(s):
s = re.sub("[\{\(\[]", '[', s)
s = re.sub("[\}\)\]]", ']', s)
answer = ''
for i,char in enumerate(s):
if char == '[':
answer += char + "'"
elif char == '[':
answer += "'" + char + "'"
elif char == ']':
answer += char
else:
answer += char
if s[i+1] in '[]':
answer += "', "
ast.literal_eval("s=%s" %answer)
return s
コメント。
from pyparsing import *
data = '(gimme [some {nested, nested [lists]}])'
opening = oneOf("({ [")
nonBracePrintables = ''.join(c for c in printables if c not in '(){}[]')
closingFor = dict(zip("({[",")}]"))
closing = Forward()
# initialize closing with an expression
closing << NoMatch()
closingStack = []
def pushClosing(t):
closingStack.append(closing.expr)
closing << Literal(closingFor[t[0]])
def popClosing():
closing << closingStack.pop()
opening.setParseAction(pushClosing)
closing.setParseAction(popClosing)
matchedNesting = nestedExpr(opening, closing, Word(alphas) | Word(nonBracePrintables))
print matchedNesting.parseString(data).asList()
プリント:更新
[['gimme', ['some', ['nested', ',', 'nested', ['lists']]]]]
:私は実際に実験として年前にそれを上に書かれていたので、私は上記の溶液を掲載。私はちょうどオリジナルの投稿を詳しく見て、それはoperatorPrecedence
メソッドで作成された再帰型定義を考えさせてくれました。元のアプローチを使用してこのソリューションを再作成しました。
from pyparsing import *
enclosed = Forward()
nestedParens = nestedExpr('(', ')', content=enclosed)
nestedBrackets = nestedExpr('[', ']', content=enclosed)
nestedCurlies = nestedExpr('{', '}', content=enclosed)
enclosed << (Word(alphas) | ',' | nestedParens | nestedBrackets | nestedCurlies)
data = '(gimme [some {nested, nested [lists]}])'
print enclosed.parseString(data).asList()
を与える:(徹底的にテストしていない、しかし右入力データと左再帰の問題がある可能性があります)
[['gimme', ['some', ['nested', ',', 'nested', ['lists']]]]]
Paul、有益な回答をありがとうございました。そして、私の新しいお気に入りのPythonライブラリを作成し、オープンソース化してくれてありがとう! pyparsingは私が取り組んでいるプロジェクトのサイズ、複雑さ、保守性を劇的に減らすのに役立っています。 – Derek
賛辞をお寄せいただきありがとうございます。 – PaulMcG