使用Lepl的解析器
我想解析一个文本文件,比如说像这样的内容:
div::
class:yo-d
text:example
id:my-class
h1:: Title
href:http://www.example.com
div::
class:class1
id:my-class2
这个格式有点像 reStructuredText。
每个 标签 都以 ::
结尾,并且可以有一些属性,像 attr:value
这样的形式。
我想得到的结果是一个 Python 字典,像这样:
{'div': {'attrs': {'text': 'example', 'class': 'yo-d', 'id': 'my-class'},
'sub': {'h1': {'content': 'Title', 'attrs': {'href': 'http://www.example.com'}},
'div': {'attrs': {'class': 'class1', 'id': 'my-class2'}},
},
}
}
在 sub 后面是缩进的标签,如果某个内容跟在标签的 ::
后面,它就会放在 'content'
里。
我想用 Lepl,但我连从哪里开始都不知道,有什么建议吗?
谢谢,
rubik
1 个回答
2
使用Lepl的一个替代方案是Pyparsing:https://github.com/pyparsing/pyparsing
我现在正在成功使用Pyparsing,如果你给结果起个名字,就可以得到包含命名结果的字典。