How to create a grammar to the following data using Pyparsing

Go To StackoverFlow.com

5

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

2012-04-04 23:47
by Cory
Yep, this is too broad a question without additional information and code - Niklas B. 2012-04-05 00:50
lepl has an example that is almost this - http://www.acooke.org/lepl/offside.html#example - but pyparsing has a much bigger community for support, so i wouldn't really suggest changing unless there's no way for pyparsing to handle indents - andrew cooke 2012-04-05 03:10
Whitespace-sensitive text is a weak spot for pyparsing. This example (http://pyparsing.wikispaces.com/file/view/indentedGrammarExample.py) on the pyparsing wiki shows one way, but it is still an awkward go - PaulMcG 2012-04-06 05:03


3

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'}}}}
2012-04-09 09:29
by fraxel
Sorry I should have mentioned that 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 - Cory 2012-04-09 16:35
@cory - ok, but you have to tell us what the differences are, otherwise it is impossible to answer the question! A better data>output example is needed ; - fraxel 2012-04-09 16:39
Ads