Python字典:需要更好的输出

4

大家好,我写了一段代码并得到了输出结果。现在,这是一个trie(字典树)。我想以美观的方式展示它。有人能帮我吗?我希望我的展示方式像这个链接中的样子:http://en.wikipedia.org/wiki/File:Trie_example.svg

但我想知道如何将这个庞大的输出转换成像这样整洁的输出[(1,2), (1,3), (1,4), (3,4)] ??

defaultdict(<type 'int'>, {'A': 1, 'W': 12})
defaultdict(<type 'int'>, {'A': 2, 'X': 25})
defaultdict(<type 'int'>, {'A': 3})
defaultdict(<type 'int'>, {'A': 4})
defaultdict(<type 'int'>, {'S': 5})
defaultdict(<type 'int'>, {'S': 6})
defaultdict(<type 'int'>, {'S': 7})
defaultdict(<type 'int'>, {'D': 8})
defaultdict(<type 'int'>, {'D': 9})
defaultdict(<type 'int'>, {'D': 10})
defaultdict(<type 'int'>, {'D': 11})
defaultdict(<type 'int'>, {})
defaultdict(<type 'int'>, {'R': 16, 'E': 13, 'F': 19})
defaultdict(<type 'int'>, {'E': 14})
defaultdict(<type 'int'>, {'E': 15})
defaultdict(<type 'int'>, {})
defaultdict(<type 'int'>, {'R': 17})
defaultdict(<type 'int'>, {'T': 18})
defaultdict(<type 'int'>, {})
defaultdict(<type 'int'>, {'F': 20})
defaultdict(<type 'int'>, {'F': 21})
defaultdict(<type 'int'>, {'D': 22})
defaultdict(<type 'int'>, {'D': 23})
defaultdict(<type 'int'>, {'D': 24})
defaultdict(<type 'int'>, {})
defaultdict(<type 'int'>, {'C': 26})
defaultdict(<type 'int'>, {'C': 27})
defaultdict(<type 'int'>, {'V': 28})
defaultdict(<type 'int'>, {'S': 29})
defaultdict(<type 'int'>, {})

我已经理解了表示部分。但是我想知道如何将这个庞大的输出转换为像这样整洁的输出[(1,2), (1,3), (1,4), (3,4)]? - Mojo_Jojo
1个回答

16

你应该尝试使用 Pydot!这个软件包可以让你创建一些图形:

import pydot 

edges = [(1,2), (1,3), (1,4), (3,4)] 
g = pydot.graph_from_edges(edges) 
g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')

The result

安装方法:

pip install pydot

(如果您喜欢)您也可以使用easy_installPyPM

pydot需要pyparsing来加载DOT文件,并需要graphviz来渲染图形。

如果您想要png图片(例如),您可以替换该行

g.write_jpeg('graph_from_edges_dot.jpg', prog='dot')

g.write('graph_from_edges_dot.png', prog='dot', format='png')
或者
g.write_png('graph_from_edges_dot.png', prog='dot')

完整文档在这里: PyDot文档


2
不用谢。如果您已经得到了想要的所有信息,可以接受答案。 - Sandro Munda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接