私たちは次の文字列pyparsingから結果を得るにはオブジェクトを転送しますか?
string = """
object obj1{
attr1 value1;
object obj2 {
attr2 value2;
}
}
object obj3{
attr3 value3;
attr4 value4;
}
"""
ネストされたオブジェクトがありますがあり、我々はこれを解析するためにフォワードを使用すると仮定しましょう。
from pyparsing import *
word = Word(alphanums)
attribute = word.setResultsName("name")
value = word.setResultsName("value")
object_grammar = Forward()
attributes = attribute + value + Suppress(";") + LineEnd().suppress()
object_type = Suppress("object ") + word.setResultsName("object_type") + Suppress('{') + LineEnd().suppress()
object_grammar <<= object_type+\
OneOrMore(attributes|object_grammar) + Suppress("}") | Suppress("};")
for i, (obj, _, _) in enumerate(object_grammar.scanString(string)):
print('\n')
print('Enumerating over object {}'.format(i))
print('\n')
print('This is the object type {}'.format(obj.object_type))
print(obj.asXML())
print(obj.asDict())
print(obj.asList())
print(obj)
print(obj.dump())
これらは結果です。 obj.asXML()関数にはすべての情報が含まれていますが、フラット化されているため、結果の解析には情報の順序が不可欠です。これはこれを行う最善の方法ですか?私は何かを欠いているに違いない。私はネストされたオブジェクトとネストされていないオブジェクトの両方で、つまりobj1、obj2、obj3の両方で動作するソリューションを希望します。
また、setResultsName('object_type')
は、親オブジェクトに対してobject_type
を返しません。上記のプログラムの出力を以下に示します。助言がありますか?
Enumerating over object 0
This is the object type obj2
<ITEM>
<object_type>obj1</object_type>
<name>attr1</name>
<value>value1</value>
<object_type>obj2</object_type>
<name>attr2</name>
<value>value2</value>
</ITEM>
{'object_type': 'obj2', 'name': 'attr2', 'value': 'value2'}
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
['obj1', 'attr1', 'value1', 'obj2', 'attr2', 'value2']
- name: attr2
- object_type: obj2
- value: value2
Enumerating over object 1
This is the object type obj3
<ITEM>
<object_type>obj3</object_type>
<name>attr3</name>
<value>value3</value>
<name>attr4</name>
<value>value4</value>
</ITEM>
{'object_type': 'obj3', 'name': 'attr4', 'value': 'value4'}
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
['obj3', 'attr3', 'value3', 'attr4', 'value4']
- name: attr4
- object_type: obj3
- value: value4
ありがとうPaul!これは素晴らしい作品です!あなたがそれを書いたので今や意味があります。上記の例は、完全なファイルのスニペットです。ファイルの先頭に 'defintion here'のような行が追加されていますが、理解すると' parseString'を使うことはできません。 's.asDict()'を使うことができないことを除いて、うまく動作する '[s、i、j for s object_grammar.scanString(string)]'を使っています。なぜasDictがうまくいかないのか? – kdheepak