这里有一个完全愚蠢的方法:import collections
string = """
apples: 20
oranges: 30
ripe: yes
farmers:
elmer fudd
lives in tv
farmer ted
lives close
farmer bill
lives far
selling: yes
veggies:
carrots
potatoes
"""
def funky_parse(inval):
lines = inval.split("\n")
items = collections.defaultdict(list)
at_val = False
key = ''
val = ''
last_indent = 0
for j, line in enumerate(lines):
indent = len(line) - len(line.lstrip())
if j != 0 and at_val and indent > last_indent > 4:
continue
if j != 0 and ":" in line:
if val:
items[key].append(val.strip())
at_val = False
key = ''
line = line.lstrip()
for i, c in enumerate(line, 1):
if at_val:
val += c
else:
key += c
if c == ':':
at_val = True
if i == len(line) and at_val and val:
items[key].append(val.strip())
val = ''
last_indent = indent
return items
print dict(funky_parse(string))
输出
^{pr2}$