【发布时间】:2016-03-04 09:29:12
【问题描述】:
我有以下形式的 Markdown 列表:
- launchers
- say hello
- command: echo "hello" | festival --tts
- icon: shebang.svg
- say world
- command: echo "world" | festival --tts
- icon: shebang.svg
- say date
- command: date | festival --tts
我有一个函数可以将此 Markdown 列表转换为字典,如下所示:
{'say world': {'command': 'echo "world" | festival --tts', 'icon': 'shebang.svg'}, 'say hello': {'command': 'echo "hello" | festival --tts', 'icon': 'shebang.svg'}, 'say date': {'command': 'date | festival --tts'}}
当我这样做时,显然顺序丢失了。保持这种顺序的适当方法是什么?一个简单的清单会好吗? OrderedDict 会更好吗?应该怎么做?
到目前为止,我所拥有的作为一个最小的工作示例如下所示:
import re
def Markdown_list_to_dictionary(Markdown_list):
line = re.compile(r"( *)- ([^:\n]+)(?:: ([^\n]*))?\n?")
depth = 0
stack = [{}]
for indent, name, value in line.findall(Markdown_list):
indent = len(indent)
if indent > depth:
assert not stack[-1], "unexpected indent"
elif indent < depth:
stack.pop()
stack[-1][name] = value or {}
if not value:
# new branch
stack.append(stack[-1][name])
depth = indent
return(stack[0])
Markdown_list =\
"""
- launchers
- say hello
- command: echo "hello" | festival --tts
- icon: shebang.svg
- say world
- command: echo "world" | festival --tts
- icon: shebang.svg
- say date
- command: date | festival --tts
"""
print(Markdown_list_to_dictionary(Markdown_list))
【问题讨论】:
-
简单回答:是的,如果您想在字典中保留您的订单,请使用
OrderedDict。使用简单的列表无法为您提供您想要的结构,因为无法将标题/呼叫名称添加到内部列表。
标签: python list markdown ordereddictionary