gpt4 book ai didi

javascript - 将python字典输出转换为流程图

转载 作者:行者123 更新时间:2023-12-03 11:09:33 24 4
gpt4 key购买 nike

我有一个文件(请参阅下面代码中的状态变量),我想将其转换为流程图(附后)。我的 python 脚本将“status”转换为字典。如何将该词典转换为流程图或图形?我的代码:

status = """
Object car {
Name honda;
From Richland;
To Seattle;
Distance 160;
Configuration road_travel;
}

Object bus {
Name greyhound;
From pasco;
To richland;
Distance 15;
Configuration road_travel;
}

Object aeroplane {
Name united;
From miami_airport;
To pasco;
Distance 1000;
Configuration air_travel;
}

Object train {
Name gas_train;
From beach;
To miami_airport;
Distance 30;
Configuration train_travel;
}
"""
sale_number = ''

sales = collections.defaultdict(list)

for line in status.split('\n'):
line = line.strip()
if line.startswith("set"):
continue
elif (line.startswith("Object") or line.startswith("object")):
sale_number = line.split(' ')[1].strip()
elif not line or line.isspace() :
continue
else:
# you can also use a regular expression here
sales[sale_number].append(line.split())

for sale in sales:
print sale+str(dict(sales[sale][:-1]))

这会生成:

car{'To': 'Seattle;', 'Configuration': 'road_travel;', 'From': 'Richland;', 'Name': 'honda;', 'Distance': '160;'}
train{'To': 'miami_airport;', 'Configuration': 'train_travel;', 'From': 'beach;', 'Name': 'gas_train;', 'Distance': '30;'}
aeroplane{'To': 'pasco;', 'Configuration': 'air_travel;', 'From': 'miami_airport;', 'Name': 'united;', 'Distance': '1000;'}
bus{'To': 'richland;', 'Configuration': 'road_travel;', 'From': 'pasco;', 'Name': 'greyhound;', 'Distance': '15;'}

我想将上面的Python输出转换成如下图所示的图片。我不想使用 Giffy 或 MS-Visio 手动执行此操作,因为我的实际案例有大约 1000 个对象(此示例在“状态”中有 4 个对象) flow_chart of above dictionary

最佳答案

仅仅专注于将格式怪异的 status 字符串转换为 dict 就已经够困难的了,难道你不能将其采用更合理、更流行的格式(例如 JSON)吗?

import re
def Status2dict(status):
result = {}
current = {}
lines = status.splitlines()
for line in lines:
line = line.strip()
if not line:
continue
mo = re.match(r'Object (\w+) {', line)
if mo:
curk = mo.group(1)
current = {curk: {}}
elif re.match('}', line):
result.update(current)
current = {}
else:
mo = re.match(r'(\w+)\s+([\w\s]+);', line)
if not mo:
raise ValueError('cannot match {!r}'.format(line))
current[curk][mo.group(1)] = mo.group(2)
if current:
result.update(current)
return result

import pprint
pprint.pprint(Status2dict(status))

此代码尝试在推断语法的微小变化上保持一定的鲁棒性,您可能需要将其调高,具体取决于。但是,有总比没有好。

关于javascript - 将python字典输出转换为流程图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27673194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com