python - 如何使用 Pyparsing 创建以下数据的语法

标签 python parsing pyparsing

我有类似于 YAML 的数据,需要使用 Pyparsing 为其创建语法。与 Python 一样,Yaml 的数据范围由空格定义

数据:

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

解析完上面的内容后,应该会输出类似这样的内容:

{'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'}}}}

[编辑] 数据类似于 YAML 但不完全相同。所以 YAML Python 解析器无法解析它。我留下了一些细节以使示例数据更简单

最佳答案

您可以使用 PyYAML 而不是 Pyparsing为此。

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

输出:

{'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'}}}}

关于python - 如何使用 Pyparsing 创建以下数据的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10020840/

相关文章:

Python: reshape 具有多个索引的数据框

python - 如何在 Python 中序列化 CObject?

javascript - 替换非渲染(非显示)元素文本中的 ↵ (\n)

python - 去除标签内容之外的文本

python - 如何使用 pyparsing 解析缩进和缩进?

python - 保留文本结构信息 - pyparsing

python - Pandas - 添加新列 - 使用循环

python - Python < 3 中是否有类似 'nonlocal' 的内容?

javascript - 使用 JavaScript 解析 URL

c - C 语言的 vhdl 解析器