Cory
Cory

Reputation: 15605

How to create a grammar to the following data using Pyparsing

I have data similar to YAML and need to create a grammar for it using Pyparsing. Like Python, Yaml's data scope is defined by the whitespace

data:

object : object_name 
comment : this object is created first 
methods:   
  method_name:
    input: 
      arg1: arg_type
      arg2: arg2_type
    output:   

  methond2_name:
    input:
    output:
      arg1 : arg_type

After parsing the above, it should output something similar to this:

{'comment': 'this object is created first',
 'object': 'object_name',
 'methods': {'method_name': {'input': {'arg1': 'arg_type', 'arg2': 'arg2_type'}, 
 'output': None}, 'methond2_name': {'input': None, 'output': {'arg1': 'arg_type'}}}}

[EDIT] The data is similar to YAML but not exactly the same. So YAML Python parser is not able to parse it. I left of some of the details to make the example data simpler

Upvotes: 5

Views: 959

Answers (1)

fraxel
fraxel

Reputation: 35269

Instead of Pyparsing you could use PyYAML for this.

import yaml
f = open('yyy.yaml', 'r')
print yaml.load(f)

output:

{'comment': 'this object is created first',
 'object': 'object_name',
 'methods': {'method_name': {'input': {'arg1': 'arg_type', 'arg2': 'arg2_type'}, 
 'output': None}, 'methond2_name': {'input': None, 'output': {'arg1': 'arg_type'}}}}

Upvotes: 3

Related Questions