4

次のような構成テキストがあります。

text="""
key1 value1
key2 { value1 value2 }
key3 subkey1 {
    key1 1
    key2 2
    key3 {
        value1
    }
}

BLOBKEY name {
    dont {
        # comment
        parse { me }
    }
}

key3 subkey2 {
    key1 value1
}

"""

値はプレーン文字列または引用符で囲まれた文字列です。キーは英数字の文字列です。私はそれを前もって知っていてkey2key3.subkey1.key4セットを保持するので、それらのパスを別の方法で扱うことができます。BLOBKEY同様に、「エスケープされた」構成セクションが含まれることを私は知っています。

目標は、次のような辞書に変換することです。

{'key1': 'value1',
 'key2': set(['value1', 'value2']),
 'key3': {
    'subkey1': {
        'key1': 1,
        'key2': 2,
        'key3': set(['value1']),
    },
    'subkey2': {
        'key1': 'value1'
    }
 },
 'BLOBKEY': {
    'name': "    dont {\n        # comment\n        parse { me }\n    }\n"
 }
}

以下のこのコードは、ネストされたリストの束に分解するのに非常に優れています。

import pyparsing
string = pyparsing.CharsNotIn("{} \t\r\n")
group = pyparsing.Forward()
group << ( 
           pyparsing.Group(pyparsing.Literal("{").suppress() + 
                           pyparsing.ZeroOrMore(group) + 
                           pyparsing.Literal("}").suppress()) |
           string
           )

toplevel = pyparsing.OneOrMore(group)

pyparsingを使用してPythonで、必要な結果を得る最良の方法は何ですか?

4

1 に答える 1

3

これが私のこれまでの進歩です。生のブロブを解析しませんが、他のすべては正しいようです。

LBRA = Literal("{").suppress()
RBRA = Literal("}").suppress()
EOL = lineEnd.suppress()
tmshString = Word(alphanums + '!#$%&()*+,-./:;<=>?@[\]^_`|~')

tmshValue = Combine( tmshString | dblQuotedString.setParseAction( removeQuotes ))
tmshKey = tmshString

def toSet(s, loc, t):
    return set(t[0])

tmshSet = LBRA + Group(ZeroOrMore(tmshValue.setWhitespaceChars(' '))).setParseAction(toSet) + RBRA

def toDict(d, l):
    if not l[0] in d:
        d[l[0]] = {}

    for v in l[1:]:
        if type(v) == list:
            toDict(d[l[0]],v)
        else:
            d[l[0]] = v

def trueDefault(s, loc, t):
    return len(t) and t or True

singleKeyValue = Forward()
singleKeyValue << (
            Group(
                tmshKey +  (
                            # A toggle value (i.e. key without value).
                            EOL.setParseAction(trueDefault) |
                            # A set of values on a single line.
                            tmshSet |
                            # A normal value or another singleKeyValue group.
                            Optional(tmshValue | LBRA + ZeroOrMore(singleKeyValue) + RBRA).setParseAction(trueDefault)
                           )
            )
)

multiKeysOneValue = Forward()
multiKeysOneValue << (
            Group(
                tmshKey + (
                            multiKeysOneValue | 
                            tmshSet  |
                            LBRA + ZeroOrMore(singleKeyValue) + RBRA
                          )
            )
)



toplevel = OneOrMore(multiKeysOneValue)

# now parse data and print results
data = toplevel.parseString(testData)

h = {}
map(lambda x:toDict(h, x), data.asList())
pprint(h)
于 2011-04-07T03:38:26.053 に答える