【发布时间】:2014-10-07 08:19:08
【问题描述】:
我有如下列表:
- launchers
- say hello
- command: echo "hello" | festival --tts
- icon: sayHello.png
- say world
- command: echo "world" | festival --tts
- icon: sayWorld.png
- wait
- command: for ((x = 0; x < 10; ++x)); do :; done
- icon: wait.png
我想将其解析为如下字典:
{
"launchers": {
"say hello": {
"command": "echo \"hello\" | festival --tts",
"icon": "sayHello.png"
}
"say world": {
"command": "echo \"world\" | festival --tts",
"icon": "sayWorld.png"
}
"wait": {
"command": "for ((x = 0; x < 10; ++x)); do :; done",
"icon": "wait.png"
}
}
}
我已经开始编写一些计算前导空格的非常手动的代码(例如len(line.rstrip()) - len(line.rstrip().lstrip())),但我想知道是否有更明智的方法来解决这个问题。我知道 JSON 可以导入 Python,但这不符合我的目的。那么,如何将文件中的 Markdown 列表解析为 Python 中的字典呢?有没有一种有效的方法来做到这一点?
这是我现在正在使用的一些基本代码:
for line in open("configuration.md", 'r'):
indentation = len(line.rstrip()) - len(line.rstrip().lstrip())
listItem = line.split('-')[1].strip()
listItemSplit = listItem.split(':')
key = listItemSplit[0].strip()
if len(listItemSplit) == 2:
value = listItemSplit[1].strip()
else:
value = ""
print(indentation, key, value)
【问题讨论】:
标签: python list parsing markdown